我可能有点迟到了,但我已经把自己的 jQuery 插件放在一起......
可通过 jsDeliver CDN 获得:https://cdn.jsdelivr.net/npm/@thelevicole/toc.js@1/dist/toc.jquery.js
页面结构的简单示例:
<div class="table-of-contents"></div>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h2>Heading 2</h2>
<h2>Heading 2</h2>
<h1>Heading 1</h1>
现在启动插件:
$('.table-of-contents').tableOfContents();
哪个会输出这个列表:
<ul class="toc-list">
<li class="toc-item">
<a href="#heading-1" class="toc-link">Heading 1</a>
<ul class="toc-list">
<li class="toc-item">
<a href="#heading-2" class="toc-link">Heading 2</a>
<ul class="toc-list">
<li class="toc-item">
<a href="#heading-3" class="toc-link">Heading 3</a>
</li>
</ul>
</li>
<li class="toc-item">
<a href="#heading-4" class="toc-link">Heading 2</a>
</li>
<li class="toc-item">
<a href="#heading-5" class="toc-link">Heading 2</a>
</li>
</ul>
</li>
<li class="toc-item">
<a href="#heading-6" class="toc-link">Heading 1</a>
</li>
</ul>
截图供参考:
有很多选项可以通过...
$('.table-of-contents').tableOfContents({
contentTarget: $( document.body ), // The element with content.
selectors: 'h1$1; h2$2; h3$3; h4$4; h5$5; h6$6;', // Tree structure.
nestingDepth: -1, // How deep we'll allow nesting. -1 for infinate.
slugLength: 40, // The max number of chars in the hash slug.
anchors: true, // Add anchors to headings.
anchorText: '#', // The symbol added to headings.
orderedList: false // True to use <ol> instead of <ul>
});
selectors 选项允许您从其他选择器创建目录,而不仅仅是 h1、h2、h3 等。
选择器选项接受选择器和深度的字符串、数组或对象:
字符串
$('.table-of-contents').tableOfContents({
// '{selector}${depth}; {selector}${depth}; ...'
selectors: 'h1$1; h2$2; h3$3; p:not(.my-class)$2; ...'
});
选择器模式相当简单,并且遵循一个简单的模式。我们首先有 DOM/CSS 选择器 {selector},然后是嵌套深度,它以美元符号 ${depth} 开始并以分号结束;
用于嵌套标题的默认模式如下所示:'h1$1; h2$2; h3$3; h4$4; h5$5; h6$6;'
数组
$('.table-of-contents').tableOfContents({
selectors: [
// '{selector}${depth}'
'h1$1',
'h2$2',
'h3$3',
'p:not(.my-class)$2',
...
]
});
对象
$('.table-of-contents').tableOfContents({
selectors: {
// '{selector}': {depth}
'h1': 1,
'h2': 2,
'h3': 3,
'p:not(.my-class)': 2,
...
}
});
自定义选择器示例:
<div class="table-of-contents"></div>
<article>
<p class="level-1">I'm level 1</p>
<p class="level-2">I'm level 2</p>
<p class="level-1">I'm level 1 again</p>
<p class="level-2">I'm level 2 again</p>
<p class="level-3">I'm level 3</p>
<p><strong>I'm a div element</strong></p>
<p class="level-2">I'm level 2</p>
</article>
$('.table-of-contents').tableOfContents({
contentTarget: 'article',
selectors: '.level-1 $1; .level-2 $2; .level-3 $3; p > strong $4'
});
将导致...
我还没有机会编写适当的文档,但您可以在 GitHub 上关注此项目:https://github.com/thelevicole/toc.js 或在此处查看主页:https://thelevicole.com/toc.js/