实现目录js
实现目录功能的 JavaScript 方法
动态生成目录结构
通过遍历 HTML 文档中的标题标签(如 h1, h2, h3 等),动态创建目录列表。使用 document.querySelectorAll 获取所有标题元素,并为每个标题生成对应的目录项。
function generateTOC() {
const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
const tocContainer = document.createElement('div');
tocContainer.id = 'toc';
headings.forEach((heading, index) => {
const level = parseInt(heading.tagName.substring(1));
const indent = (level - 1) * 20;
const tocItem = document.createElement('div');
tocItem.style.marginLeft = `${indent}px`;
tocItem.innerHTML = `<a href="#${heading.id || `heading-${index}`}">${heading.textContent}</a>`;
tocContainer.appendChild(tocItem);
});
document.body.prepend(tocContainer);
}
平滑滚动效果
为目录链接添加平滑滚动行为,提升用户体验。使用 scrollIntoView 方法实现平滑滚动效果。
document.querySelectorAll('#toc a').forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href').substring(1);
const targetElement = document.getElementById(targetId);
targetElement.scrollIntoView({ behavior: 'smooth' });
});
});
自动高亮当前阅读位置

监听滚动事件,根据当前视口位置高亮对应的目录项。通过比较元素位置与视口位置,确定当前阅读的章节。
window.addEventListener('scroll', function() {
const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
let currentHeading = null;
headings.forEach(heading => {
const rect = heading.getBoundingClientRect();
if (rect.top >= 0 && rect.top <= 200) {
currentHeading = heading;
}
});
if (currentHeading) {
document.querySelectorAll('#toc a').forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === `#${currentHeading.id}`) {
link.classList.add('active');
}
});
}
});
CSS 样式增强
为目录添加基本样式,包括字体、间距和活动状态指示。

#toc {
position: fixed;
left: 20px;
top: 20px;
background: white;
padding: 10px;
border: 1px solid #ddd;
max-width: 300px;
max-height: 80vh;
overflow-y: auto;
}
#toc a {
display: block;
padding: 5px 0;
color: #333;
text-decoration: none;
}
#toc a.active {
font-weight: bold;
color: #0066cc;
}
响应式设计考虑
添加媒体查询确保目录在不同设备上都能正常显示和使用。
@media (max-width: 768px) {
#toc {
position: static;
max-width: 100%;
margin-bottom: 20px;
}
}
初始化调用
在页面加载完成后自动生成目录。
document.addEventListener('DOMContentLoaded', function() {
generateTOC();
});






