我应该使用“名称"还是“id"制作 HTML 锚点? [英] Should I make HTML Anchors with 'name' or 'id'?
问题描述
当人们想用http://example.com/#foo
"方法引用网页的某个部分时,应该使用
When one wants to refer to some part of a webpage with the "http://example.com/#foo
" method, should one use
<h1><a name="foo"/>Foo Title</h1>
或
<h1 id="foo">Foo Title</h1>
它们都有效,但它们是平等的,还是它们有语义差异?
They both work, but are they equal, or do they have semantic differences?
推荐答案
根据 HTML 5 规范,5.9.8 导航到片段标识符:
According to the HTML 5 specification, 5.9.8 Navigating to a fragment identifier:
对于 HTML 文档(和 text/html MIME 类型),必须遵循以下处理模型来确定文档的指示部分是什么.
For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is.
- 解析 URL,让 fragid 成为
;URL 的组成部分. - 如果 fragid 是空字符串,则文档的指定部分是文档的顶部.
- 如果 DOM 中有一个元素的 ID 正好等于 fragid,那么树序中的第一个这样的元素就是文档的指定部分;在这里停止算法.
- 如果 DOM 中有一个 a 元素,它的 name 属性的值正好等于 fragid,那么树序中的第一个这样的元素就是文档的指定部分;在这里停止算法.
- 否则,文档中没有指明部分.
- Parse the URL, and let fragid be the <fragment> component of the URL.
- If fragid is the empty string, then the indicated part of the document is the top of the document.
- If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
- If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
- Otherwise, there is no indicated part of the document.
所以,它会寻找id="foo"
,然后会跟着name="foo"
So, it will look for id="foo"
, and then will follow to name="foo"
正如@hsivonen 所指出的,在 HTML5 中 a
元素没有 name 属性.但是,上述规则仍然适用于其他命名元素.
As pointed out by @hsivonen, in HTML5 the a
element has no name attribute. However, the above rules still apply to other named elements.
这篇关于我应该使用“名称"还是“id"制作 HTML 锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!