原生JavaScript实现导航栏单链接active类排他性切换
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
- We select all navbar links using
document.querySelectorAll()just like before. - For each link, we add a click event listener.
- When a link is clicked:
- We loop through every link and remove the
activeclass from each one. - We then add the
activeclass to the specific link that was clicked.
This ensures only one link has theactiveclass at any time, exactly what you need!
- We loop through every link and remove the
内容的提问来源于stack exchange,提问作者Emmanuel

