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

如何在滚动时切换active类?锚点点击联动导航active类实现

Hey there! Let's tackle your two navigation issues one by one—getting the active-desktop class to toggle on scroll, and syncing it with anchor link jumps. Here's how to solve both:

1. Toggle active-desktop on Scroll

We'll listen for the window's scroll event, check which section is currently in view, and update the navigation's active state accordingly.

First, confirm each anchor link corresponds to a section with the matching ID (you already have this with #about-section, #pp-section, etc.). Then add this JavaScript:

// Listen for scroll events
$(window).scroll(function() {
  // Get current scroll position (add a buffer to trigger active state earlier)
  const scrollPos = $(window).scrollTop() + 100;

  // Loop through each navigation link
  $('.top-nav-links li a').each(function() {
    const targetHref = $(this).attr('href');

    // Handle the Home link (since it points to /index.html, not an anchor)
    if (targetHref === '/index.html') {
      // Activate Home when we're at the top of the page (before the About section)
      if (scrollPos < $('#about-section').offset().top) {
        $('.top-nav-links li').removeClass('active-desktop');
        $(this).parent().addClass('active-desktop');
      }
      return; // Skip to next link
    }

    // Handle anchor links
    if (targetHref.startsWith('#')) {
      const targetSection = $(targetHref);
      const sectionTop = targetSection.offset().top;
      const sectionBottom = sectionTop + targetSection.outerHeight();

      // Check if scroll position is within the target section's bounds
      if (scrollPos >= sectionTop && scrollPos < sectionBottom) {
        $('.top-nav-links li').removeClass('active-desktop');
        $(this).parent().addClass('active-desktop');
      }
    }
  });
});

// Initialize active state on page load
$(document).ready(function() {
  $(window).scroll(); // Trigger scroll handler once to set initial state
});

Notes:

  • The + 100 in scrollPos adds a small buffer so the active state switches a little before the section hits the top of the viewport—adjust this number to match your design needs.
  • We explicitly handle the Home link separately since it doesn't point to an anchor on the page.

Your existing click handler works for setting the active state on click, but we can enhance it to ensure the active state stays synced after the scroll animation finishes (and add smooth scrolling for a better user experience):

$('.top-nav-links li a').click(function(e) {
  const targetHref = $(this).attr('href');

  // Handle Home link (direct page navigation)
  if (targetHref === '/index.html') {
    window.location.href = targetHref;
    return;
  }

  // Prevent default anchor jump to enable smooth scrolling
  e.preventDefault();

  const targetSection = $(targetHref);
  const sectionTop = targetSection.offset().top - 80; // Subtract nav height to avoid overlap

  // Smooth scroll to target section
  $('html, body').animate({
    scrollTop: sectionTop
  }, 500, () => {
    // Ensure active state is set after scroll completes
    $('.top-nav-links li').removeClass('active-desktop');
    $(this).parent().addClass('active-desktop');
  });

  // Set active state immediately on click (avoids delay during scroll)
  $('.top-nav-links li').removeClass('active-desktop');
  $(this).parent().addClass('active-desktop');
});

Notes:

  • The - 80 in sectionTop accounts for your navigation bar's height—adjust this so the section doesn't get hidden under the nav after scrolling.
  • We set the active state both on click and after the scroll finishes to keep the UI consistent throughout the interaction.

Put all this JavaScript together, and your navigation should now correctly toggle the active-desktop class both on scroll and when clicking anchor links!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:45:25