简体   繁体   English

HTML锚链接作为名称而不是ID

[英]HTML anchor link as name and not id

is it possible to add skip to content to link to name and not for id? 是否可以添加跳至内容以链接到名称而不是ID?

<a id="skiptocontent" href="#main" class="">skip to main content</a>
<h1 name="main">Main</h1>

No, this is not possible. 不,这是不可能的。 There are some work-arounds: 有一些解决方法:

1. Add id property 1.添加id属性

Obviously, you could add the id property to the target element: 显然,您可以将id属性添加到目标元素:

<h1 name="main" id="main">Main</h1>

2. Add an anchor 2.添加锚点

If the target needs to be identified by name, add an anchor: 如果需要通过名称标识目标,请添加锚点:

<a name="main"/><h1>Main</h1>

But in HTML5 the name attribute for the a element is obsolete . 但是在HTML5中, a元素的name属性已过时

3. Use scripting to add the id attribute 3.使用脚本添加id属性

You could add a script that will add the missing id attribute on page load: 您可以添加一个脚本,该脚本将在页面加载时添加缺少的id属性:

<script>
    // find first element that has the name attribute set to "main":
    var element = document.querySelector('[name=main]');
    // copy that value into the id attribute
    element.setAttribute('id', element.getAttribute('name')); 
</script>

You should then put this script block at the end of the document, so just before the closing </body> tag. 然后,应将此脚本块放在文档的末尾,即在</body>标记之前。

4. Add script to the source link: 4.将脚本添加到源链接:

You could replace the href value with a script that will do the action based on the name attribute: 您可以使用将根据name属性执行操作的脚本替换href值:

<a id="skiptocontent" 
   href="javascript:document.querySelector('[name=main]').scrollIntoView();" 
   class="">skip to main content</a>

Remark 备注

As you tagged the question with HTML5, it should be noted that in HTML5 there is a clear moving away from using the name attribute as a target. 当您使用HTML5标记问题时,应注意的是,在HTML5中,显然没有使用name属性作为目标。 id attributes are preferred in HTML5. 在HTML5中首选id属性。 That makes sense, because name values do not have to be unique, while id values have to be. 这是有道理的,因为name值不必唯一,而id值必须唯一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM