Highlight table of content item when scroll page

This commit is contained in:
Folyd 2020-12-19 16:32:04 +08:00
parent d54579046f
commit b1646773dd
2 changed files with 67 additions and 24 deletions

View file

@ -1,26 +1,5 @@
.rse-fix-readme {
display: flex;
padding-right: 0 !important;
}
.rse-version-list {
min-width: 220px;
padding: 0 1rem;
border-left: var(--color-border-secondary) solid 1px;
margin-left: 1.5rem;
max-height: 100vh;
position: sticky;
top: 0;
overflow: scroll !important;
font-size: 13px;
list-style: none;
color: var(--color-text-primary);
background-color: var(--color-bg-canvas);
z-index: 999;
}
.rse-version-list-item {
padding: 0.5rem 0;
padding: 0.5rem 1rem;
}
.rse-version-list-item:not(:last-child) {
@ -37,4 +16,31 @@
font-size: 16px;
font-weight: bold;
margin: 0.3rem 0;
}
.rse-active {
border-left: solid #f9826c 2px;
}
@media screen and (min-width: 1280px) {
.rse-fix-readme {
display: flex;
padding-right: 0 !important;
}
.rse-version-list {
box-sizing: content-box;
min-width: 220px;
border-left: var(--color-border-secondary) solid 1px;
margin-left: 1.5rem;
max-height: 100vh;
position: sticky;
top: 0;
overflow: scroll !important;
font-size: 13px;
list-style: none;
color: var(--color-text-primary);
background-color: var(--color-bg-canvas);
z-index: 999;
}
}

View file

@ -15,7 +15,7 @@
let html = `
<div style="display: flex">
<span><a href="${version.anchor}"><b>${version.number}</b></a></span>
<a href="${version.anchor}"><b>${version.number}</b></a>
<span class="rse-version-date Counter">${version.date}</span>
</div>
`;
@ -23,7 +23,7 @@
.filter(v => v.minor === version.minor && v.major === version.major && v.fix !== "0")
.sort((a, b) => parseInt(a.fix) - parseInt(b.fix));
if (fixVersions && fixVersions.length > 0) {
fixVersions = fixVersions.map(fv => `<small><a href="${fv.anchor}">${fv.number}</a></small>`).join(" , ");
fixVersions = fixVersions.map(fv => `<a href="${fv.anchor}"><small>${fv.number}</small></a>`).join(" , ");
html += `<div style="margin-top: 0.3rem">${fixVersions}</div>`;
}
@ -44,8 +44,45 @@
readme.classList.add("rse-fix-readme");
readme.appendChild(ul);
});
highlight();
})();
function highlightNav(id) {
document.querySelectorAll(".rse-version-list-item").forEach((item) => {
item.classList.remove("rse-active");
});
let a = document.querySelector(`.rse-version-list-item a[href$="${id}"]`);
if (a) {
a.parentElement.parentElement.classList.add("rse-active");
}
}
function highlight() {
let elementArr = {};
let currentHeading = "";
window.onscroll = () => {
document.querySelectorAll('.markdown-body>h1>a').forEach(item => {
if (item.href !== "") {
let url = new URL(item.href);
elementArr[url.hash] = item.getBoundingClientRect().top;
}
});
for (let id in elementArr) {
if (!elementArr.hasOwnProperty(id)) {
continue;
}
if (elementArr[id] > 0 && elementArr[id] < 300) {
if (currentHeading !== id) {
highlightNav(id);
currentHeading = id;
}
break;
}
}
}
}
function parseVersion(title) {
let text = title.textContent;