简体   繁体   English

当前与 JS ES6 的活动链接

[英]Current Active Link with JS ES6

Im currently trying to fix up my Nav bar so that the current link will have a class of 'active' applied to it.我目前正在尝试修复我的导航栏,以便当前链接将应用一类“活动”。

I have managed to set up the toggle but I'm really struggling to find resources on how to clear the class off the other links.我已经设法设置了切换,但我真的很难找到有关如何从其他链接中清除类的资源。

Everything on here seems to primarily be focused on JQuery which I am intentionally trying to avoid.这里的所有内容似乎都主要集中在 JQuery 上,我有意避免这种情况。

Here is my code:这是我的代码:

<div class="navbar">
        <a href="#" class="toggle" id="nav-hamburger">
            <i class="fas fa-bars"></i>
            <a href="#" class="brand">Appeal Digital</a>
        </a>
        <div class="links">
                <a href="#" class="link active">Home</a>
                <a href="#" class="link">Who are we?</a>
                <a href="#" class="link">Meet the Team</a>
                <a href="#" class="link">Contact Us</a>
        </div> 
    </div>


const toggleBtn = document.querySelector('#nav-hamburger');
toggleBtn.addEventListener('click', (el) => {

    //TOGGLE NAV BUTTON
    const links = document.querySelector('.links');
    links.classList.toggle('links-show');
});

const links = document.getElementsByClassName('link');

for(let el of links) {

    el.addEventListener('click', (e) => {
        el.classList.remove('active');
        el.classList.toggle('active');    

    });
}

I would remove all .active classes if you click on a menu link and set the .active class for clicked link.如果您单击菜单链接并为单击的链接设置 .active 类,我将删除所有 .active 类。

 const links = document.querySelectorAll('.links > a'); const changeActive = (e) => { [...links].forEach(link => link.classList.remove('active')); e.target.classList.add('active'); } [...links].forEach(e => e.addEventListener('click', changeActive));
 .active { font-weight: bold; }
 <div class="navbar"> <a href="#" class="toggle" id="nav-hamburger"> <i class="fas fa-bars"></i> <a href="#" class="brand">Appeal Digital</a> </a> <div class="links"> <a href="#" class="link active">Home</a> <a href="#" class="link">Who are we?</a> <a href="#" class="link">Meet the Team</a> <a href="#" class="link">Contact Us</a> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM