簡體   English   中英

HTML錨鏈接作為名稱而不是ID

[英]HTML anchor link as name and not id

是否可以添加跳至內容以鏈接到名稱而不是ID?

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

不,這是不可能的。 有一些解決方法:

1.添加id屬性

顯然,您可以將id屬性添加到目標元素:

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

2.添加錨點

如果需要通過名稱標識目標,請添加錨點:

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

但是在HTML5中, a元素的name屬性已過時

3.使用腳本添加id屬性

您可以添加一個腳本,該腳本將在頁面加載時添加缺少的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>

然后,應將此腳本塊放在文檔的末尾,即在</body>標記之前。

4.將腳本添加到源鏈接:

您可以使用將根據name屬性執行操作的腳本替換href值:

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

備注

當您使用HTML5標記問題時,應注意的是,在HTML5中,顯然沒有使用name屬性作為目標。 在HTML5中首選id屬性。 這是有道理的,因為name值不必唯一,而id值必須唯一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM