这段代码用于在用户滚动页面时,根据当前滚动位置高亮相应的导航链接。它的作用是判断当前页面的滚动位置是否在某个 section 的范围内,如果在这个范围内,就为对应的导航链接添加 active 类,从而实现导航链接的高亮。
html代码如下:
<div class="nav">
<a href="#section1">section1</a>
<a href="#section2">section2</a>
<a href="#section3">section3</a>
</div>
<div id="section1" class="section">
section1xxxxxxxxxxxxxxxxxx
</div>
<div id="section2" class="section">
section2xxxxxxxxxxxxxxxxxx
</div>
<div id="section3" class="section">
section3xxxxxxxxxxxxxxxxxx
</div>
css代码如下:
<style>
.nav {
width: 80%;
margin: auto;
display: flex;
column-gap: 20px;
justify-content: center;
position: sticky;
top: 0;
}
.nav a {
color: black;
}
.nav a.active {
color: aquamarine;
}
.section {
height: 800px;
width: 80%;
margin: auto;
border: 1px solid #eee;
margin-top: 20px;
}
</style>
js代码如下:
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', () => {
const navLink = document.querySelectorAll('.nav a');
const sections = document.querySelectorAll('.section');
function updateNav(currentPosition) {
navLink.forEach(link => {
link.classList.remove('active');
const section = document.querySelector(link.hash);
if (section.offsetTop <= currentPosition && section.offsetTop + section.offsetHeight >
currentPosition) {
link.classList.add('active');
}
})
}
window.addEventListener('scroll', () => {
let currentPosition = window.scrollY || document.documentElement.scrollTop;
updateNav(currentPosition);
})
navLink.forEach(link => {
link.addEventListener('click', e => {
e.preventDefault();
const section = document.querySelector(link.hash);
section.scrollIntoView({
behavior: 'smooth'
});
})
})
})
</script>