为何实现滚动切换导航栏当前项current类的jQuery函数无法正常工作?
Hey there! Let's troubleshoot why your nav menu's current class isn't switching correctly when scrolling. I’ve spotted a couple of key issues in your code, plus some tweaks to make the logic more robust:
1. Incorrect Method to Get Section Top Position
First off, jQuery doesn’t have a .top() method for elements—you need to use .offset().top to get the distance of the element from the top of the document. Your original code uses $home_section.top() which is invalid, so that’s a big reason the highlighting isn’t triggering.
2. Overly Simplified Highlighting Logic
Right now, your code adds the current class whenever the scroll position is greater than a section’s top. That means once you scroll past the home section, both home and about (and later contact) will all have the current class at the same time. We need to adjust the logic to only highlight the section that’s currently in view.
Corrected Code
Here’s a revised version that fixes both issues, plus makes the code more scalable for future sections:
$(function () { $(document).scroll(function () { // Add a small offset to make the highlight switch feel more natural const scrollPosition = $(this).scrollTop() + 50; // Loop through each nav item and its corresponding section $('.nav-item').each(function() { const targetSectionId = $(this).attr('href'); const $targetSection = $(targetSectionId); // Get the section's top and bottom boundaries const sectionTop = $targetSection.offset().top; const sectionBottom = sectionTop + $targetSection.outerHeight(); // Toggle the current class only if scroll is within the section's range $(this).toggleClass('current', scrollPosition >= sectionTop && scrollPosition < sectionBottom); }); }); });
Key Improvements:
- Uses
offset().topto correctly fetch each section’s top position - Calculates the section’s bottom boundary with
outerHeight()to check if the scroll position is inside the section - Uses a loop to handle all nav items at once—no need to repeat code for each section
- Adds a 50px offset so the highlight switches when the section is partially visible (adjust this number to match your design needs)
Quick Setup Note:
Make sure your nav links have a consistent class (like nav-item) and their href matches the corresponding section’s ID. For example:
<a href="#home" class="nav-item home">Home</a> <a href="#about" class="nav-item about">About</a> <a href="#contact" class="nav-item contact">Contact</a> <section id="home">...</section> <section id="about">...</section> <section id="contact">...</section>
内容的提问来源于stack exchange,提问作者mazz

