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

将原生JS滚动导航栏代码转为jQuery遇阻,请求技术协助

Fixing Your Navbar Scroll Class Toggle with 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(), and toggleClass() methods automatically apply to every element in the collection—no manual looping needed!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:30:39