onscroll函数触发时导航栏字体颜色不变化问题排查(背景颜色正常生效)
解决导航栏滚动时字体颜色不变化的问题
我一眼就发现问题所在了——你通过document.querySelectorAll('.nav-links')获取到的是一个NodeList集合(包含所有匹配.nav-links的元素),而不是单个DOM元素。直接给这个集合调用classList.add()或者remove()是不会生效的,因为这些类操作方法只能作用在单个元素上!
修正后的JavaScript代码
const navbar = document.getElementById('navbar'); const navbarText = document.querySelectorAll('.nav-links') window.onscroll = () => { if (window.scrollY > 500) { navbar.classList.add('nav-active'); // 遍历每个导航链接,逐个添加样式类 navbarText.forEach(link => link.classList.add('nav-text-active')); } else { navbar.classList.remove('nav-active'); // 遍历每个导航链接,逐个移除样式类 navbarText.forEach(link => link.classList.remove('nav-text-active')); } };
额外检查项
别忘了确认你的CSS中已经正确定义了.nav-text-active的样式,比如:
.nav-text-active { color: #333; /* 替换成你想要的滚动后的字体颜色 */ }
这样修改后,滚动页面时导航栏的字体颜色就能和背景色一起正常切换啦!
内容的提问来源于stack exchange,提问作者Stasa Bastrica
相关产品推荐
相关产品推荐

