我应该使用“名称"或"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?
推荐答案
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为< fragment> 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
元素没有名称属性.但是,以上规则仍适用于其他命名元素.
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屋!