具有“名称”或“id”的html锚点?


当使用“http://example.com/#foo”方法引用某个网页的某个部分时,是否应该使用

<h1><a name="foo"/>Foo Title</h1>

<h1 id="foo">Foo Title</h1>

他们都工作,但他们是平等的,还是有语义上的差异?

根据HTML 5规范,[5.9.8导航到片段标识符](“http://www.w3.org/html/wg/drafts/html/master/browsers.html

#scroll-to-fragid”rel):

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.

>

  • Parse the URL, and let fragid be the 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” **

编辑:正如@hsivonen指出的,在HTML5中,a元素没有name属性。但是,上述规则仍然适用于其他指定的元素。

在用作text / html的任何HTML格式中,您都不应该使用&lt; h1&gt;&lt; a name =“foo”/&gt; Foo
Title&lt; / h1&gt; ,因为 text / html 中不支持XML空元素语法。不过,在HTML4中,&lt; h1&gt;&lt;
a name =“foo”&gt; Foo标题&lt; / a&gt;&lt; / h1&gt; `是可以的。目前草拟的HTML5无效。

在HTML4和HTML5中,&lt; h1 id =“foo”&gt; Foo标题&lt; / h1&gt;都可以。这在Netscape
4中不会奏效,但是您可能会使用其他一些在Netscape 4中不起作用的功能。

未经作者同意,本文严禁转载,违者必究!