一套 JS 自动生成目录的完整方案(可直接用)
预览
https://www.oleou.com/zt/tocbot/HTML 目录容器
在你的侧栏或正文中放一个容器:
<div id="toc" class="toc"></div>
✅ JS 自动生成目录(支持层级、自动编号、平滑滚动)
<script> // 自动生成目录 document.addEventListener("DOMContentLoaded", function () { const content = document.querySelector(".post-content"); // 正文内容容器 const toc = document.querySelector("#toc"); // TOC 容器 if (!content || !toc) return; const headings = content.querySelectorAll("h1, h2, h3, h4, h5, h6"); if (!headings.length) return; let tocHtml = '<ul class="toc-list">'; headings.forEach((h, index) => { const tag = h.tagName.toLowerCase(); const id = "heading-" + index; h.setAttribute("id", id); const level = parseInt(tag.replace("h", "")); // h2 → 2 tocHtml += ` <li class="toc-item toc-level-${level}"> <a href="#${id}">${h.innerText}</a> </li>`; }); tocHtml += "</ul>"; toc.innerHTML = tocHtml; // 平滑滚动 document.querySelectorAll('#toc a').forEach(a => { a.addEventListener("click", function (e) { e.preventDefault(); document.querySelector(this.getAttribute("href")) .scrollIntoView({ behavior: "smooth" }); }); }); }); </script>
目录(TOC)样式 — Bootstrap 风格(可选)
<style>
.toc {
padding: 1rem;
border-left: 3px solid var(--bs-primary);
background: rgba(0,0,0,0.03);
border-radius: .5rem;
font-size: 0.95rem;
}
.toc-list {
list-style: none;
padding-left: 0;
margin: 0;
}
.toc-item {
margin: .25rem 0;
}
.toc-level-1 { margin-left: 0; font-weight: bold; }
.toc-level-2 { margin-left: 1rem; }
.toc-level-3 { margin-left: 2rem; }
.toc-level-4 { margin-left: 3rem; }
.toc-level-5 { margin-left: 4rem; }
.toc-level-6 { margin-left: 5rem; }
.toc a {
text-decoration: none;
color: var(--bs-primary);
}
.toc a:hover {
text-decoration: underline;
}
</style>
使用方法总结
正文外层加 .post-content右侧放 <div id="toc"></div>
引入上面那段 JS
样式可选