首页 > 解决方案 > 导航栏活动选项卡颜色更改

问题描述

我的代码不起作用我不知道为什么?

有人,请帮帮我。

我无法将类名添加到活动导航栏

<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';
    }
}

标签: javascripthtmlcssnavigation

解决方案


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


推荐阅读