[英]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:
有一些解决方法:
id
property id
属性 Obviously, you could add the id
property to the target element: 显然,您可以将
id
属性添加到目标元素:
<h1 name="main" id="main">Main</h1>
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
属性已过时 。
id
attribute 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>
标记之前。
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>
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.