如何在单击时更改导航栏中的链接颜色

x33g5p2x  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(315)

我想在点击导航栏时更改链接(a)的颜色,如果我导航到另一个链接(b),则链接(a)的颜色应返回默认值。

links.forEach( a=>{ //Its Color Changes But I Want All The Others To Be In Default Color 
    a.onclick = () => {
        a.classList.add("active");
    }
})
sqyvllje

sqyvllje1#

links.forEach(a=> {
    a.onclick = () => {
        links.forEach(a=>a.classList.remove('active'));
        a.classList.add("active");
    }
})
aurhwmvo

aurhwmvo2#

向每个元素添加事件,然后单击链接执行类的添加/删除。

var navElements = document.querySelectorAll('a');
      //looping through each anchor element
      navElements.forEach(function(element){
           //adding click event on each anchor element
            element.addEventListener('click',function(e){
                 //stop default behaviour
                 e.preventDefault();
                 //select current active element
                 let active = document.querySelector('.selected');
                 active?.classList.remove('selected'); //remove class  
                 this.classList.add('selected'); //add class to current click element
      });
});

相关问题