diff --git a/docs/theme/pagetoc.js b/docs/theme/pagetoc.js index d6df2848..b7e5c7a7 100644 --- a/docs/theme/pagetoc.js +++ b/docs/theme/pagetoc.js @@ -1,11 +1,11 @@ -var forEach = function (elems, fun) { +function forEach(elems, fun) { Array.prototype.forEach.call(elems, fun); -}; +} // Un-active everything when you click it -var forPagetocElem = function (fun) { +function forPagetocElem(fun) { forEach(document.getElementsByClassName("pagetoc")[0].children, fun); -}; +} forPagetocElem(function (el) { el.addEventHandler("click", function () { @@ -16,11 +16,23 @@ forPagetocElem(function (el) { }); }); +function getRect(element) { + return element.getBoundingClientRect(); +} + +function overflowTop(container, element) { + return getRect(container).top - getRect(element).top; +} + +function overflowBottom(container, element) { + return getRect(container).bottom - getRect(element).bottom; +} + var updateFunction = function () { var id; var elements = document.getElementsByClassName("header"); forEach(elements, function (el) { - if (window.scrollY >= el.offsetTop) { + if (window.scrollY + 100 >= el.offsetTop) { id = el; } }); @@ -28,10 +40,18 @@ var updateFunction = function () { forPagetocElem(function (el) { el.classList.remove("active"); }); + if (!id) return; forPagetocElem(function (el) { if (id.href.localeCompare(el.href) == 0) { el.classList.add("active"); + let pagetoc = document.getElementsByClassName("pagetoc")[0]; + if (overflowTop(pagetoc, el) > 0) { + pagetoc.scrollTop = el.offsetTop; + } + if (overflowBottom(pagetoc, el) < 0) { + pagetoc.scrollTop -= overflowBottom(pagetoc, el); + } } }); };