1 回答
TA贡献1770条经验 获得超3个赞
您给出的错误是由第一个链接引起的。
href 是#这样的link.hash属性""
两者都document.querySelector("")引发document.querySelector("#")错误。解决方案是在散列不为空时添加检查。
if (link.hash != "" && link.hash != "#") {
请注意,Home链接将始终保持活动状态,因为它没有相应的<div id="home">元素
window.addEventListener('scroll', event => {
let navigationLinks = document.querySelectorAll('nav ul li a');
let fromTop = window.scrollY;
navigationLinks.forEach(link => {
if (link.hash != "" && link.hash != "#") {
let section = document.querySelector(link.hash);
if (section.offsetTop <= fromTop &&
section.offsetTop + section.offsetHeight > fromTop
) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
}
})
});
nav a.active {
color: darkcyan;
border-bottom: 2px solid darkgoldenrod;
}
/* for demonstration purposes */
nav {
position: fixed;
top: 0;
}
#about,
#contact {
height: 100vh;
}
<nav>
<ul class="nav-links">
<li><a class="active" href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<section>
<div id="about">About</div>
<div id="contact">Contact</div>
</section>
添加回答
举报