css 制作目录
使用纯CSS制作目录
通过CSS的counter-reset和counter-increment属性可以自动生成目录编号,结合锚点实现跳转功能。
<div class="toc">
<h3>目录</h3>
<ul>
<li><a href="#section1">章节一</a></li>
<li><a href="#section2">章节二</a></li>
<li><a href="#section3">章节三</a></li>
</ul>
</div>
<style>
.toc {
counter-reset: section;
border-left: 3px solid #3498db;
padding-left: 15px;
}
.toc ul {
list-style: none;
padding: 0;
}
.toc li::before {
counter-increment: section;
content: counter(section) ". ";
color: #e74c3c;
}
.toc a {
text-decoration: none;
color: #2c3e50;
transition: color 0.3s;
}
.toc a:hover {
color: #3498db;
}
</style>
美化目录样式
添加悬停效果和过渡动画增强用户体验。
.toc {
background-color: #f8f9fa;
border-radius: 5px;
padding: 20px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.toc li {
padding: 8px 0;
border-bottom: 1px dashed #ddd;
}
.toc li:last-child {
border-bottom: none;
}
.toc a:hover {
padding-left: 5px;
}
响应式目录设计
使用媒体查询适应不同屏幕尺寸。
@media (max-width: 768px) {
.toc {
position: fixed;
top: 0;
left: -250px;
width: 250px;
height: 100vh;
transition: left 0.3s;
z-index: 1000;
}
body.toc-active .toc {
left: 0;
}
}
嵌套多级目录
通过CSS计数器实现多级嵌套编号。
<ul class="toc-multi">
<li>一级标题
<ul>
<li>二级标题</li>
<li>二级标题</li>
</ul>
</li>
</ul>
<style>
.toc-multi {
counter-reset: level1;
}
.toc-multi > li::before {
counter-increment: level1;
content: counter(level1) ". ";
}
.toc-multi ul {
counter-reset: level2;
padding-left: 20px;
}
.toc-multi ul li::before {
counter-increment: level2;
content: counter(level1) "." counter(level2) " ";
}
</style>
浮动目录实现
创建始终可见的浮动目录。
.toc-float {
position: fixed;
right: 20px;
top: 50%;
transform: translateY(-50%);
max-height: 80vh;
overflow-y: auto;
background: white;
padding: 15px;
border: 1px solid #eee;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.toc-float::-webkit-scrollbar {
width: 5px;
}
.toc-float::-webkit-scrollbar-thumb {
background: #ccc;
}
动态高亮当前章节
使用JavaScript配合CSS实现阅读进度指示。
window.addEventListener('scroll', function() {
const sections = document.querySelectorAll('section');
const links = document.querySelectorAll('.toc a');
sections.forEach((sec, index) => {
const rect = sec.getBoundingClientRect();
if(rect.top <= 100 && rect.bottom >= 100) {
links[index].classList.add('active');
} else {
links[index].classList.remove('active');
}
});
});
.toc a.active {
color: #e74c3c;
font-weight: bold;
border-left: 3px solid #e74c3c;
padding-left: 10px;
}






