css制作目录
使用CSS制作目录的方法
基础HTML结构
创建一个简单的HTML结构,包含标题和对应的锚点链接。
<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>
<div id="section1">
<h2>第一部分</h2>
<p>内容...</p>
</div>
<div id="section2">
<h2>第二部分</h2>
<p>内容...</p>
</div>
<div id="section3">
<h2>第三部分</h2>
<p>内容...</p>
</div>
基本CSS样式
为目录添加基础样式,如字体、间距和颜色。
.toc {
background-color: #f9f9f9;
border: 1px solid #ddd;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.toc h3 {
margin-top: 0;
color: #333;
}
.toc ul {
list-style-type: none;
padding-left: 0;
}
.toc li {
margin-bottom: 8px;
}
.toc a {
text-decoration: none;
color: #0066cc;
}
.toc a:hover {
text-decoration: underline;
}
美化目录样式
添加更复杂的美化样式,如悬停效果和层级缩进。
.toc {
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.toc ul ul {
padding-left: 20px;
}
.toc a {
display: block;
padding: 5px 10px;
transition: background-color 0.3s;
}
.toc a:hover {
background-color: #f0f0f0;
color: #004499;
}
响应式目录设计
确保目录在不同屏幕尺寸下都能正常显示。
@media (max-width: 768px) {
.toc {
width: 100%;
box-sizing: border-box;
}
.toc ul {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.toc li {
margin-bottom: 0;
}
}
固定定位目录
创建固定在页面一侧的目录,方便长文档导航。
.toc {
position: fixed;
top: 20px;
right: 20px;
width: 250px;
max-height: 80vh;
overflow-y: auto;
}
@media (max-width: 1024px) {
.toc {
position: static;
width: auto;
max-height: none;
}
}
动态高亮当前章节
使用JavaScript和CSS结合,高亮显示当前浏览的章节。
.toc a.active {
font-weight: bold;
color: #003366;
background-color: #e6f2ff;
border-left: 3px solid #0066cc;
}
window.addEventListener('scroll', function() {
const sections = document.querySelectorAll('div[id^="section"]');
const links = document.querySelectorAll('.toc a');
sections.forEach(section => {
const rect = section.getBoundingClientRect();
if (rect.top <= 100 && rect.bottom >= 100) {
links.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === `#${section.id}`) {
link.classList.add('active');
}
});
}
});
});
多级嵌套目录样式
为包含多级子目录的情况设计样式。
.toc ul ul {
margin-top: 5px;
border-left: 1px dashed #ccc;
}
.toc ul ul a {
font-size: 0.9em;
color: #666;
}
.toc ul ul a:hover {
color: #004499;
}
打印优化样式
确保目录在打印时也能正常显示。
@media print {
.toc {
page-break-after: avoid;
break-after: avoid;
}
.toc a::after {
content: " (第" target-counter(attr(href), page) "页)";
}
}






