簡體   English   中英

帶有錨鏈接的 Js 目錄不會滾動到所需的標簽

[英]Js Table of Content with anchor link does not scroll to desired tag

我有一個小的 JS 代碼,可以檢測 h1 到 h6 標簽並提供目錄。 問題是單擊標題(例如標題 5)只是將頁面滾動到頂部,而我希望它滾動到標題 5。我是 JS 的新手,所以我不確定我是否做錯事。

感謝您的回復和建議,謝謝。


編輯

感謝 MrUpsidown 的建議,將 id 添加到 h1 標簽,現在腳本可以運行了。 我不知道這是否是好的做法,所以我歡迎提出改進腳本的建議。

 var headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); var toc = document.createElement('div'); toc.id = 'toc'; document.body.appendChild(toc); for (var i = 0; i < headings.length; i++) { var heading = headings[i]; var anchor = document.createElement('a'); anchor.href = '#' + heading.id; anchor.innerHTML = heading.innerHTML; toc.appendChild(anchor); }
 #toc { display: flex; flex-direction: column; flex-wrap: nowrap; } #toc > a { padding: 10px; } #toc > a:hover { background: gray; color: #fff; }
 <h1 id="one">Title 1</h1> <p>Sample Text 1</p> <h1 id="two">Title 2</h1> <p>Sample Text 2</p> <h1 id="three">Title 3</h1> <p>Sample Text 3</p> <h1 id="four">Title 4</h1> <p>Sample Text 4</p> <h1 id="five">Title 5</h1> <p>Sample Text 5</p> <h1 id="six">Title 6</h1> <p>Sample Text 6</p>

您當然可以使用 Javascript 執行此操作,盡管我寧願嘗試輸出具有唯一和自定義 ID 的 HTML。

在你的循環中,創建一個自定義標題

let title = 'title'+ (i+1); // Create ids of title1, title2, etc.

然后使用計算出的標題設置標題 HTML id 屬性

heading.id = title; // Set heading id with title

最后用計算出的標題設置錨 href

anchor.href = '#' + title; // Set href with title

 var headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); var toc = document.createElement('div'); toc.id = 'toc'; document.body.appendChild(toc); for (var i = 0; i < headings.length; i++) { var heading = headings[i]; let title = 'title'+ (i+1); // Create ids of title1, title2, etc. heading.id = title; // Set heading id with title var anchor = document.createElement('a'); anchor.href = '#' + title; // Set href with title anchor.innerHTML = heading.innerHTML; toc.appendChild(anchor); }
 #toc { display: flex; flex-direction: column; flex-wrap: nowrap; } #toc > a { padding: 10px; } #toc > a:hover { background: gray; color: #fff; }
 <h1>Title 1</h1> <p>Sample Text 1</p> <h1>Title 2</h1> <p>Sample Text 2</p> <h1>Title 3</h1> <p>Sample Text 3</p>

暫無
暫無

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

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