js实现目录链接,内容跟着目录滚动显示
时间: 2024-02-18 20:04:30 浏览: 13
要实现目录链接和内容跟着目录滚动显示,可以使用JavaScript和CSS来实现。下面是一个简单的示例代码:
HTML:
```
<div class="wrapper">
<div class="table-of-contents">
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
</div>
<div class="content">
<div id="section1">
<h2>Section 1</h2>
<p>Content for section 1 goes here.</p>
</div>
<div id="section2">
<h2>Section 2</h2>
<p>Content for section 2 goes here.</p>
</div>
<div id="section3">
<h2>Section 3</h2>
<p>Content for section 3 goes here.</p>
</div>
</div>
</div>
```
CSS:
```
.wrapper {
display: flex;
flex-direction: row;
height: 100vh;
}
.table-of-contents {
flex: 0 0 200px;
overflow-y: scroll;
}
.content {
flex: 1;
overflow-y: scroll;
}
.content > div {
padding: 50px;
}
```
JavaScript:
```
document.addEventListener('DOMContentLoaded', function() {
var sections = document.querySelectorAll('.content > div');
var links = document.querySelectorAll('.table-of-contents a');
window.addEventListener('scroll', function() {
var currentSection = '';
sections.forEach(function(section) {
var sectionTop = section.offsetTop;
var sectionHeight = section.offsetHeight;
if (window.pageYOffset >= sectionTop - sectionHeight / 3) {
currentSection = section.getAttribute('id');
}
});
links.forEach(function(link) {
link.classList.remove('active');
if (link.getAttribute('href').substring(1) === currentSection) {
link.classList.add('active');
}
});
});
});
```
这段代码会监听页面滚动事件,当滚动到某个内容区域时,会自动将对应的目录链接高亮显示。同时,点击目录链接也会自动滚动到对应的内容区域。