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

如何实现平滑滚动导航并根据用户浏览位置高亮对应导航项

实现滚动时导航自动高亮的方案

你可以直接在原有平滑滚动代码的基础上追加滚动监听逻辑即可,完整实现如下:

1. 补充current类高亮样式(如果还未定义)

aside li a.current {
  color: #ff4400;
  font-weight: bold;
  /* 可根据设计需求自行调整高亮样式 */
}

2. 替换原有jQuery代码

替换后的代码同时保留你原有的平滑滚动功能,新增了滚动时自动匹配当前区块并高亮导航的逻辑:

$(document).ready(function(){
  // 原有平滑滚动逻辑
  $('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    let target  = this.hash,
        $target = $(target);
    $('html, body').stop().animate({
      'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
      window.location.hash = target;
    });
  });

  // 新增滚动导航高亮逻辑
  let scrollTimer = null;
  const $sections = $('#main h2');
  const $navLinks = $('aside li a');

  $(window).on('scroll', function() {
    // 节流处理,减少滚动事件触发频率,降低性能消耗
    if (scrollTimer) clearTimeout(scrollTimer);
    scrollTimer = setTimeout(() => {
      let scrollTop = $(window).scrollTop();
      // 倒序遍历区块,优先匹配可视区域内最靠下的区块,避免滚动到底部时高亮异常
      $($sections.get().reverse()).each(function() {
        // 这里的减100是偏移量,有固定头部的话可以改成头部的高度,匹配更精准
        if (scrollTop >= $(this).offset().top - 100) {
          let currentId = '#' + $(this).attr('id');
          $navLinks.removeClass('current');
          $navLinks.filter(`[href="${currentId}"]`).addClass('current');
          return false;
        }
      })
    }, 100);
  })
});

参数调整说明

  • 代码里的偏移量- 100可以根据你的页面布局调整,比如页面顶部有固定导航栏,就把这个值改成导航栏的高度,高亮触发的位置会更符合视觉预期
  • 节流间隔100单位是毫秒,数值越小高亮响应越灵敏,性能消耗也会相应提高,可根据实际情况调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:27:03