可以通过 npm 或直接引入脚本文件来安装 Tocify。
npm install tocify
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tocify/dist/jquery.tocify.css">
<script src="https://cdn.jsdelivr.net/npm/jquery"></script>
<script src="https://cdn.jsdelivr.net/npm/tocify"></script>
以下是一个基本示例,展示如何使用 Tocify 自动生成页面目录:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tocify Example</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tocify/dist/jquery.tocify.css">
<style>
body {
display: flex;
}
#toc {
width: 250px;
position: fixed;
}
#content {
margin-left: 260px;
}
</style>
</head>
<body>
<div id="toc"></div>
<div id="content">
<h1>Section 1</h1>
<p>Content for section 1...</p>
<h2>Subsection 1.1</h2>
<p>Content for subsection 1.1...</p>
<h1>Section 2</h1>
<p>Content for section 2...</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery"></script>
<script src="https://cdn.jsdelivr.net/npm/tocify"></script>
<script>
$(function() {
$("#toc").tocify({
context: "#content",
selectors: "h1,h2"
});
});
</script>
</body>
</html>
Tocify 提供了多种配置选项,以下是一些常用的配置项:
$("#toc").tocify({
context: "body", // TOC 生成的上下文
selectors: "h1,h2,h3", // 要包含在 TOC 中的标题
smoothScroll: true, // 启用平滑滚动
scrollTo: 0, // 滚动时的偏移量
extendPage: true, // 页面内容较少时,延长页面高度
hashGenerator: "compact", // 生成锚点的方式("compact"、"pretty" 或自定义函数)
highlightOnScroll: true, // 滚动时高亮当前标题
highlightOffset: 40 // 高亮当前标题的偏移量
});
Tocify 可以在动态内容加载后重新生成 TOC:
$("#toc").tocify();
$("#content").on("DOMNodeInserted", function() {
$("#toc").tocify("refresh");
});
你可以通过 CSS 自定义 Tocify 的外观:
.tocify-header {
font-weight: bold;
}
.tocify-subheader {
margin-left: 20px;
}
Tocify 提供了一些事件,可以在 TOC 生成或更新时进行处理:
$("#toc").tocify({
selectors: "h1,h2,h3",
showEffect: "slideDown",
hideEffect: "slideUp",
showAndHide: true
}).on("tocify:show", function() {
console.log("TOC item shown");
}).on("tocify:hide", function() {
console.log("TOC item hidden");
});