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

如何判断距离页面顶部最近的区块 为导航对应链接添加active类

导航滚动激活功能修复方案

原代码核心问题

  • 滚动位置取值兼容性错误:document.body.scrollTop 在Chrome、Firefox等浏览器的标准模式下返回值恒为0,无法获取到真实滚动距离
  • 位置计算逻辑错误:getBoundingClientRect().y 本身就是元素相对于当前视口顶部的距离,不需要再减去滚动位置,原判断条件的边界逻辑完全错误
  • 区块高度累加逻辑无效:循环内累加pos变量的逻辑和当前区块的位置判断没有关联,无法正确匹配当前可视区域对应的区块

修复后可直接运行的代码

// 提前获取所有区块和对应的导航元素,不要在滚动事件里重复查询DOM
const sec = document.querySelectorAll('section'); // 替换为你页面实际的区块选择器
const list = document.querySelectorAll('.nav-item'); // 替换为你页面实际的导航项选择器

// 节流函数,避免滚动事件高频触发导致性能问题
const throttle = (fn, delay = 100) => {
  let timer = null;
  return function(...args) {
    if (timer) return;
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay)
  }
}

document.addEventListener("scroll", throttle(function() {
  // 兼容不同浏览器的滚动高度取值
  const scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
  for (let i = 0; i < sec.length; i++) {
    const currentSec = sec[i];
    // 获取区块相对于文档顶部的上下边界
    const secTop = currentSec.offsetTop;
    const secBottom = secTop + currentSec.offsetHeight;
    // 判断当前滚动位置是否落在当前区块范围内,减10是预留偏移容错
    if (scrollPos >= secTop - 10 && scrollPos < secBottom - 10) {
      list[i].classList.add("active");
    } else {
      list[i].classList.remove("active");
    }
  }
}));

// 首屏加载完成后主动触发一次计算,避免刚打开页面时没有对应激活项
window.addEventListener('load', () => {
  document.dispatchEvent(new Event('scroll'))
})

可选适配调整

如果你的页面有固定顶部的导航栏,可将判断条件里的偏移值调整为导航栏的实际高度,避免区块被导航栏遮挡时的匹配误差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:24:03