From 2c6a95a75567714c88f8aa6685230285939743ba Mon Sep 17 00:00:00 2001 From: ZhenShuo Leo <98386542+ZhenShuo2021@users.noreply.github.com> Date: Sun, 5 Oct 2025 03:36:10 +0800 Subject: [PATCH] fix(toc): incorrect active link in short paragraph --- layouts/partials/toc.html | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/layouts/partials/toc.html b/layouts/partials/toc.html index 9946f6d8..316d764d 100644 --- a/layouts/partials/toc.html +++ b/layouts/partials/toc.html @@ -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,