fix: fix incorrect TOC highlight (fix #249)

This commit is contained in:
saicaca
2024-12-07 21:59:17 +08:00
parent e44628364b
commit cbf17e880d

View File

@@ -217,20 +217,19 @@ class TableOfContents extends HTMLElement {
this.activeIndicator = document.getElementById("active-indicator"); this.activeIndicator = document.getElementById("active-indicator");
this.sections = Array.from(
document.querySelectorAll("section")
);
this.tocEntries = Array.from( this.tocEntries = Array.from(
document.querySelectorAll<HTMLAnchorElement>("#toc a[href^='#']") document.querySelectorAll<HTMLAnchorElement>("#toc a[href^='#']")
); );
this.sections = new Array(this.tocEntries.length);
this.headings = new Array(this.tocEntries.length); this.headings = new Array(this.tocEntries.length);
for (let i = 0; i < this.tocEntries.length; i++) { for (let i = 0; i < this.tocEntries.length; i++) {
const id = decodeURIComponent(this.tocEntries[i].hash?.substring(1)); const id = decodeURIComponent(this.tocEntries[i].hash?.substring(1));
const section = document.getElementById(id)?.parentElement; const heading = document.getElementById(id);
if (section instanceof HTMLElement) { const section = heading?.parentElement;
this.headings[i] = section; if (heading instanceof HTMLElement && section instanceof HTMLElement) {
this.headings[i] = heading;
this.sections[i] = section;
this.headingIdxMap.set(id, i); this.headingIdxMap.set(id, i);
} }
} }