猿问

JavaScript-在滚动时更改导航样式

我希望在滚动页面时突出显示活动部分。


但我收到错误消息:“未捕获的 DOMException:无法在‘文档’上执行‘querySelector’:提供的选择器为空。”


为什么?如何解决这个问题?


js:


window.addEventListener('scroll', event=>{

    let navigationLinks = document.querySelectorAll('nav ul li a');

    let fromTop = window.scrollY;


    navigationLinks.forEach(link=>{

        let section = document.querySelector(link.hash);

        if (section.offsetTop <=fromTop &&

            section.offsetTop + section.offsetHeight > fromTop

        ){

            link.classList.add('active');

        } else{link.classList.remove('active');}

    })

});

HTML:


<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"></div>

   <div id="contact"></div>

</section>

CSS:


nav a.active{

    color: darkcyan;

    border-bottom: 2px solid darkgoldenrod;

}


梵蒂冈之花
浏览 89回答 1
1回答

德玛西亚99

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

相关分类

JavaScript
我要回答