需求背景
在长页面中,通过滚动位置自动切换顶部导航栏的激活状态,提升用户体验。
实现思路
监听窗口的滚动事件,计算当前滚动距离与各个区块的位置关系,动态更新导航项的激活状态。
代码实现
HTML 结构
<header></header>
<ul class="nav">
<li class="item active">1</li>
<li class="item">2</li>
<li class="item">3</li>
</ul>
<div class="container">
<section>1</section>
<section>2</section>
<section>3</section>
</div>
JavaScript 逻辑
const navItems = document.querySelectorAll('.nav .item');
const sections = document.querySelectorAll('.container section');
window.addEventListener('scroll', () => {
let currentIndex = -1;
sections.forEach((section, index) => {
const top = section.offsetTop;
if (window.scrollY >= top - 60) {
currentIndex = index;
}
});
navItems.forEach(item => item.classList.remove('active'));
if (currentIndex !== -1 && navItems[currentIndex]) {
navItems[currentIndex].classList.add('active');
}
});


