将原生JS滚动导航栏代码转为jQuery遇阻,请求技术协助
Hey there! Let's break down what's going wrong with your original code and convert it to working jQuery.
First, the issue with your native JS code
Your original code uses document.querySelectorAll() which returns a NodeList (a collection of elements), but then you try to call classList.add() directly on that collection. NodeLists don't have a classList property—you need to loop through each element in the collection to modify their classes. This is probably why your attempts to convert it to jQuery weren't working either; you might have missed that you're dealing with multiple elements.
Working jQuery Implementation
jQuery makes handling collections of elements much easier because its methods automatically iterate over all matched elements. Here's the correct jQuery version:
function initUpdateNavbarOnScroll() { // Cache the jQuery object for better performance const $navbarLinks = $('#site-navigation-wrap .dropdown-menu>li>a'); // Listen for the scroll event on the window $(window).scroll(function() { // Check if scroll position is at or above window height const isScrolledEnough = $(window).scrollTop() >= $(window).innerHeight(); // Add or remove the class based on the condition if (isScrolledEnough) { $navbarLinks.addClass('darklinker'); } else { $navbarLinks.removeClass('darklinker'); } }); } // Initialize the function initUpdateNavbarOnScroll();
Even More Concise Version
You can use jQuery's toggleClass() method with a second boolean parameter to simplify the code further:
function initUpdateNavbarOnScroll() { const $navbarLinks = $('#site-navigation-wrap .dropdown-menu>li>a'); $(window).scroll(function() { // Toggle the class directly based on the scroll condition $navbarLinks.toggleClass( 'darklinker', $(window).scrollTop() >= $(window).innerHeight() ); }); } initUpdateNavbarOnScroll();
Why This Works
$('#site-navigation-wrap .dropdown-menu>li>a')selects all matching anchor elements and returns a jQuery collection.$(window).scroll()attaches the scroll event listener.$(window).scrollTop()gets the current vertical scroll position, and$(window).innerHeight()gets the height of the viewport.- jQuery's
addClass(),removeClass(), andtoggleClass()methods automatically apply to every element in the collection—no manual looping needed!
内容的提问来源于stack exchange,提问作者Ronan G

