You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JavaScript实现导航栏单链接active类排他性切换

Fixing Navbar Active State Toggle Issue

Hey there! I see what you're trying to do with your navbar active state—right now your code uses toggle() which will add/remove the class on the same link when clicked, but it doesn't handle removing the class from other links. Let's fix that so only one link is active at a time.

The Problem with Your Current Code

Your existing JavaScript uses link.classList.toggle('active'), which works for toggling the class on a single link, but it doesn't clear the active class from all other links first. That means you could end up with multiple links having the active class if you click around.

Updated Solution

Here's the revised JavaScript that will handle removing the active class from all links before adding it to the clicked one:

const links = document.querySelectorAll('.navbar ul li a');

links.forEach((link) => {
  link.addEventListener('click', () => {
    // First, remove 'active' class from ALL links
    links.forEach(link => link.classList.remove('active'));
    // Then add 'active' class to the clicked link
    link.classList.add('active');
  });
});

Your Existing HTML & CSS (No Changes Needed)

Your HTML structure and CSS styling are already good to go—here they are for reference:

HTML:

<div class="navbar"> 
  <ul> 
    <li><a href="#" class="active">Homepage</a></li> 
    <li><a href="#">Blog Entries</a></li> 
    <li><a href="#">Food Gallery</a></li> 
    <li><a href="#">Contact Us</a></li> 
  </ul> 
</div>

CSS:

.active { 
  background-color: #fc9d03; 
}

How It Works

  1. We select all navbar links using document.querySelectorAll() just like before.
  2. For each link, we add a click event listener.
  3. When a link is clicked:
    • We loop through every link and remove the active class from each one.
    • We then add the active class to the specific link that was clicked.
      This ensures only one link has the active class at any time, exactly what you need!

内容的提问来源于stack exchange,提问作者Emmanuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 19:42:34