Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. Web API
  3. Document
  4. Document:anchors 属性

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

Document:anchors 属性

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

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

HTMLCollection

示例

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></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

浏览器兼容性

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp