diff --git a/static/js/main.js b/static/js/main.js index 718b599..1c94001 100644 --- a/static/js/main.js +++ b/static/js/main.js @@ -88,9 +88,7 @@ document.addEventListener("DOMContentLoaded", () => ); const scrollActiveItemIntoView = (link, behavior = "auto") => { - const item = link?.closest("li"); - - if (!item) { + if (!link) { return; } @@ -100,8 +98,10 @@ document.addEventListener("DOMContentLoaded", () => return; } - const itemLeft = item.offsetLeft; - const itemCenter = itemLeft + (item.offsetWidth / 2); + const listRect = list.getBoundingClientRect(); + const linkRect = link.getBoundingClientRect(); + const itemLeft = linkRect.left - listRect.left + list.scrollLeft; + const itemCenter = itemLeft + (linkRect.width / 2); const maxScrollLeft = list.scrollWidth - list.clientWidth; const targetLeft = Math.max(0, Math.min(maxScrollLeft, itemCenter - (list.clientWidth / 2))); @@ -140,10 +140,13 @@ document.addEventListener("DOMContentLoaded", () => }; updateActive(); + links.forEach((link) => { + link.addEventListener("click", () => scrollActiveItemIntoView(link, "smooth")); + }); window.addEventListener("scroll", () => updateActive("smooth"), { passive: true }); window.addEventListener("resize", updateActive); }; setupKangarooEye(); setupToc(); -}); \ No newline at end of file +});