带'name'或'id'的HTML锚点? [英] 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中有一个名称属性的值与fragid完全相同的 a 元素,那么树中第一个这样的元素是文件的指明部分;在这里停止算法。
- 否则,文档中没有指定的部分。
- 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.
这篇关于带'name'或'id'的HTML锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!