Document:anchors 属性

已弃用: 不再推荐使用该特性。虽然一些浏览器仍然支持它,但也许已从相关的 web 标准中移除,也许正准备移除或出于兼容性而保留。请尽量不要使用该特性,并更新现有的代码;参见本页面底部的兼容性表格以指导你作出决定。请注意,该特性随时可能无法正常工作。

Document 接口的 anchors 只读属性返回文档中所有锚点的列表。

示例

js
if (document.anchors.length >= 5) {
  dump("发现了许多锚点");
}

以下是一个示例,它可以自动将页面上的每个锚点填充到目录中:

html
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <title>测试</title>
    <script>
      function init() {
        const toc = document.getElementById("toc");
        for (const anchor of document.anchors) {
          const li = document.createElement("li");
          const newAnchor = document.createElement("a");
          newAnchor.href = "#" + anchor.name;
          newAnchor.textContent = anchor.text;
          li.appendChild(newAnchor);
          toc.appendChild(li);
        }
      }
    </script>
  </head>
  <body onload="init()">
    <h1>标题</h1>
    <h2><a name="contents">内容</a></h2>
    <ul id="toc"></ul>

    <h2><a name="plants">植物</a></h2>
    <ol>
      <li>苹果</li>
      <li>橙子</li>
      <li></li>
    </ol>

    <h2><a name="veggies">蔬菜</a></h2>
    <ol>
      <li>胡萝卜</li>
      <li>西芹</li>
      <li>节奏</li>
    </ol>
  </body>
</html>

在 JSFiddle 中查看

备注

出于向后兼容性的原因,返回的锚点集合只包含使用 name 属性创建的锚点,而不包含使用 id 属性创建的锚点。

规范

Specification
HTML
# dom-document-anchors

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
anchors
Deprecated

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Deprecated. Not for use in new websites.
Has more compatibility info.