Skip to content

Commit 556069a

Browse files
committed
正确识别小标题
1 parent 9828d61 commit 556069a

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

packages/pure/components/pages/TOC.astro

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,34 @@ const toc = generateToc(headings)
4848
constructor() {
4949
super()
5050

51-
// Initialize the headings and tocLinks
51+
// 1. Get the correct top-level headings for interaction.
5252
this.headings = Array.from(
53-
document.querySelectorAll('article h1, article h2, article h3, article h4, article h5, article h6')
54-
)
55-
this.tocLinks = Array.from(this.querySelectorAll('a[href^="#"]')).map((link) => ({
53+
document.querySelectorAll('#content > h1, #content > h2, #content > h3, #content > h4, #content > h5, #content > h6')
54+
) as HTMLElement[];
55+
56+
const validSlugs = new Set(this.headings.map(h => h.id));
57+
58+
// 2. Filter the visible TOC links based on the valid slugs.
59+
const allLinks = Array.from(this.querySelectorAll('a[href^="#"]'));
60+
allLinks.forEach(link => {
61+
const slug = (link.getAttribute('href') || '').substring(1);
62+
if (!validSlugs.has(slug)) {
63+
// Hide the parent <li> element of the invalid link.
64+
link.parentElement?.style.setProperty('display', 'none');
65+
}
66+
});
67+
68+
// 3. Initialize the tocLinks array with only the visible links.
69+
this.tocLinks = allLinks
70+
.filter(link => {
71+
const slug = (link.getAttribute('href') || '').substring(1);
72+
return validSlugs.has(slug);
73+
})
74+
.map((link) => ({
5675
element: link as HTMLAnchorElement,
5776
progressBar: link.previousElementSibling as HTMLElement,
5877
slug: (link.getAttribute('href') || '').substring(1)
59-
}))
78+
}));
6079
}
6180

6281
updatePositionAndStyle = () => {

0 commit comments

Comments
 (0)