可以通过 npm 安装 Tocbot,也可以直接引入 CDN 链接。
npm install tocbot
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.css">
<script src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js"></script>
首先,在你的 HTML 文件中创建一个用于放置目录的容器,并确保内容中有需要生成目录的标题标签:
<div class="toc"></div>
<article class="content">
<h1>Title 1</h1>
<p>Some content here...</p>
<h2>Sub-title 1.1</h2>
<p>Some more content...</p>
<h2>Sub-title 1.2</h2>
<p>Even more content...</p>
<h1>Title 2</h1>
<p>Content under title 2...</p>
</article>
在你的 JavaScript 文件中或<script/> 标签中初始化 Tocbot:
tocbot.init({
// Where to render the table of contents.
tocSelector: '.toc',
// Where to grab the headings to build the table of contents.
contentSelector: '.content',
// Which headings to grab inside of the contentSelector element.
headingSelector: 'h1, h2, h3'
});
Tocbot 提供了多种配置选项,以下是一些常用的选项:
tocbot.init({
tocSelector: '.toc',
contentSelector: '.content',
headingSelector: 'h1, h2, h3, h4',
ignoreSelector: '.ignore',
scrollSmooth: true,
scrollSmoothDuration: 600,
scrollEndCallback: function(e) { console.log('Scrolling finished!', e); }
});
可以通过覆盖默认的 CSS 样式来定制目录的外观。以下是一些常见的样式调整:
/* 修改目录背景色 */
.toc {
background-color: #f9f9f9;
}
/* 修改目录字体大小 */
.toc .toc-list-item {
font-size: 14px;
}
/* 修改当前激活的目录项样式 */
.toc .is-active-link {
color: #d9534f;
}
如果页面中的内容是动态加载的,生成目录后需要手动刷新 Tocbot:
// 动态加载内容后,调用 refresh 方法
tocbot.refresh();