fix(toc): incorrect active link in short paragraph

This commit is contained in:
ZhenShuo Leo
2025-10-05 03:36:10 +08:00
parent fefb7d2fb5
commit 2c6a95a755

View File

@@ -33,12 +33,24 @@
const TOC_LINK_SELECTOR = 'a[href^="#"]'
const NESTED_LIST_SELECTOR = 'li ul'
const ACTIVE_CLASS = 'active'
let isJumpingToAnchor = false
function getActiveAnchorId(anchors, offsetRatio) {
const threshold = window.scrollY + window.innerHeight * offsetRatio
const tocLinks = [...document.querySelectorAll('#TableOfContents a[href^="#"]')]
const tocIds = new Set(tocLinks.map(link => link.getAttribute('href').substring(1)))
if (isJumpingToAnchor) {
for (let i = 0; i < anchors.length; i++) {
const anchor = anchors[i]
if (!tocIds.has(anchor.id)) continue
const top = anchor.getBoundingClientRect().top + window.scrollY
if (Math.abs(window.scrollY - top) < 100) {
return anchor.id
}
}
}
for (let i = anchors.length - 1; i >= 0; i--) {
const top = anchors[i].getBoundingClientRect().top + window.scrollY
if (top <= threshold && tocIds.has(anchors[i].id)) {
@@ -85,6 +97,12 @@
toc.querySelectorAll(NESTED_LIST_SELECTOR).forEach(ul => ul.style.display = 'none')
}
links.forEach(link => {
link.addEventListener('click', () => {
isJumpingToAnchor = true
})
})
const config = {
toc,
anchors,