目的:
- 实现点击导航栏内容页面滑动到对应内容区域
- 页面滑动到某一区域,导航栏对应内容颜色发生改变
HTML代码:
导航栏设置id,内容区域设置对应id,实现查询
<nav>
<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>
</nav>
<section id="section1">Section 1 Content</section>
<section id="section2">Section 2 Content</section>
<section id="section3">Section 3 Content</section>
CSS代码:
实现滑动到某一区域,对应导航栏字体颜色发生改变
/* 添加导航栏选中状态的样式 */
nav a.active {
color: red;
}
JS代码:
这段代码通过遍历所有导航链接,为每个链接添加了一个点击事件监听器。当用户点击导航链接时,会执行以下操作:
- e.preventDefault(); 阻止默认的链接跳转行为
- const targetId = this.getAttribute('href'); 获取被点击链接的href属性,即目标内容的id
- document.querySelector(targetId).scrollIntoView({ behavior: 'smooth' }); 将页面平滑滚动到对应ID的内容区域。
document.querySelectorAll('nav a').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href');
document.querySelector(targetId).scrollIntoView({
behavior: 'smooth'
});
});
});
这段代码添加了一个滚动事件监听器,当页面滚动时会执行以下操作:
- 遍历所有的<section>元素,找到当前可见内容对应的部分的id,并将其存储在current变量中
- 遍历所有导航链接,移除它们的"active"类,然后根据current变量的值,为对应的导航链接添加"active"类,以标记当前所在位置
window.addEventListener('scroll', function() {
const sections = document.querySelectorAll('section');
let current = '';
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= sectionTop - sectionHeight / 3) {
current = section.getAttribute('id');
}
});
document.querySelectorAll('nav a').forEach(a => {
a.classList.remove('active');
if (a.getAttribute('href').slice(1) === current) {
a.classList.add('active');
}
});
});