[英]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>
不,這是不可能的。 有一些解決方法:
id
屬性 顯然,您可以將id
屬性添加到目標元素:
<h1 name="main" id="main">Main</h1>
如果需要通過名稱標識目標,請添加錨點:
<a name="main"/><h1>Main</h1>
但是在HTML5中, a
元素的name
屬性已過時 。
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>
標記之前。
您可以使用將根據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.