From cbf17e880d95a3cf76c0cd24fb8a0fc940c83641 Mon Sep 17 00:00:00 2001 From: saicaca Date: Sat, 7 Dec 2024 21:59:17 +0800 Subject: [PATCH] fix: fix incorrect TOC highlight (fix #249) --- src/components/widget/TOC.astro | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/components/widget/TOC.astro b/src/components/widget/TOC.astro index 004ace3be..c33e8dabe 100644 --- a/src/components/widget/TOC.astro +++ b/src/components/widget/TOC.astro @@ -217,20 +217,19 @@ class TableOfContents extends HTMLElement { this.activeIndicator = document.getElementById("active-indicator"); - this.sections = Array.from( - document.querySelectorAll("section") - ); - this.tocEntries = Array.from( document.querySelectorAll("#toc a[href^='#']") ); + this.sections = new Array(this.tocEntries.length); this.headings = new Array(this.tocEntries.length); for (let i = 0; i < this.tocEntries.length; i++) { const id = decodeURIComponent(this.tocEntries[i].hash?.substring(1)); - const section = document.getElementById(id)?.parentElement; - if (section instanceof HTMLElement) { - this.headings[i] = section; + const heading = document.getElementById(id); + const section = heading?.parentElement; + if (heading instanceof HTMLElement && section instanceof HTMLElement) { + this.headings[i] = heading; + this.sections[i] = section; this.headingIdxMap.set(id, i); } }