javascript - 导航栏活动选项卡颜色更改
问题描述
我的代码不起作用我不知道为什么?
有人,请帮帮我。
我无法将类名添加到活动导航栏
<nav class="navbar">
<ul>
<li class="nav-list"><a href="home.html" class="navlink">Home</a></li>
<li class="nav-list"><a href="aboutme.html" class="navlink">About me</a></li>
<li class="nav-list"><a href="work.html" class="navlink">Work</a></li>
<li class="nav-list"><a href="contact.html" class="navlink">Contact me</a></li>
</ul>
</nav>
css
.nav-list a.active{
color:rgb(28, 162, 224);
}
脚本
const currentlocation = location.href;
const menuitem = document.querySelectorAll('nav-list a');
const menulenght = menuitem.length;
for(let i = 0; i < menulenght; i++){
if(menuitem[i].href === currentlocation){
menuitem[i].className = 'active';
}
}
解决方案
1)你必须使用.
类选择器:
document.querySelectorAll( '.nav-list a' );
2)您必须使用add
方法添加一个新类:
menuitem[i].classList.add( "active" )
JS
const currentlocation = location.href;
const menuitem = document.querySelectorAll( '.nav-list a' );
for ( let i = 0; i < menuitem.length; i++ ) {
if ( menuitem[i].href === currentlocation ) {
menuitem[i].classList.add( "active" )
}
}
此外,您当前的代码中有一个错字:lenght
而不是length
推荐阅读
- reactjs - 如何在不使用组件的情况下更改 URL?
- excel - Laravel - 数据表从过滤数据中导出 excel
- reactjs - 不变量失败:找不到 ID 为 [droppable] 的可丢弃条目
- javascript - 如何将我的通话条件更改为开关盒
- reactjs - 如何在 react-hook-form 7 的寄存器中传递变量
- android - 在片段更改时恢复窗口插图
- excel - 如何使用公式删除空白单元格?
- php - 为什么我不能从我的网站下载 RSS 提要,但可以从家里的 localhost 下载
- c - setsockopt 的目的到底是什么?
- javascript - array.reduce() 但需要为返回值设置一个键