enhance toc scroll algorithm

This commit is contained in:
Reorx 2022-04-10 01:19:23 +08:00
parent 9ebe2111f6
commit 829bb01691
1 changed files with 15 additions and 16 deletions

View File

@ -138,14 +138,11 @@
<script> <script>
window.addEventListener('DOMContentLoaded', function (event) { window.addEventListener('DOMContentLoaded', function (event) {
const headings = document.querySelectorAll('h1[id],h2[id],h3[id],h4[id],h5[id]'); const headings = document.querySelectorAll('h1[id],h2[id],h3[id],h4[id],h5[id]');
const activeClass = 'active';
// Make the first header active // Make the first header active
let activeHeading = headings[0]; let activeHeading = headings[0];
function getLinkByHeading(heading) { getLinkByHeading(activeHeading).classList.add(activeClass);
const id = encodeURI(heading.getAttribute('id')).toLowerCase();
return document.querySelector(`.toc ul li a[href="#${id}"]`);
}
getLinkByHeading(activeHeading).classList.add('active');
window.addEventListener('scroll', () => { window.addEventListener('scroll', () => {
const passedHeadings = []; const passedHeadings = [];
@ -158,26 +155,28 @@ window.addEventListener('DOMContentLoaded', function (event) {
} }
} }
if (passedHeadings.length > 0) { if (passedHeadings.length > 0) {
activeHeading = passedHeadings[passedHeadings.length - 1]; newActiveHeading = passedHeadings[passedHeadings.length - 1];
}
headings.forEach(heading => {
if (heading === activeHeading) {
getLinkByHeading(heading).classList.add('active');
} else { } else {
getLinkByHeading(heading).classList.remove('active'); newActiveHeading = headings[0];
}
if (activeHeading != newActiveHeading) {
getLinkByHeading(activeHeading).classList.remove(activeClass);
activeHeading = newActiveHeading;
getLinkByHeading(activeHeading).classList.add(activeClass);
} }
})
}, false); }, false);
function getLinkByHeading(heading) {
const id = encodeURI(heading.getAttribute('id')).toLowerCase();
return document.querySelector(`.toc ul li a[href="#${id}"]`);
}
function getOffsetTop(heading) { function getOffsetTop(heading) {
if (!heading.getClientRects().length) { if (!heading.getClientRects().length) {
return 0; return 0;
} }
let rect = heading.getBoundingClientRect(); let rect = heading.getBoundingClientRect();
return rect.top return rect.top
// let win = heading.ownerDocument.defaultView;
// return rect.top + win.pageYOffset;
} }
}, false); }, false);
</script> </script>