<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>
<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>