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

如何使用jQuery检测用户是否滚动到指定ID元素,解决刷新判定不准问题

问题原因

你在window.load阶段计算的各元素getBoundingClientRect().top是相对于当前视口顶部的相对值,而非元素到整个文档顶部的固定距离:

  • 页面从顶部加载时,视口顶=文档顶,这个值刚好等于元素到文档顶的距离,判断正常
  • 页面刷新前已经有滚动偏移时,视口顶低于文档顶,你存储的bestellen等数值会比真实的元素文档顶距离小,导致滚动判断阈值错误,触发时机提前
修正方案

将元素相对视口的距离加上当前页面的滚动高度,换算为元素到文档顶部的固定值即可,修正后代码如下:

// 换成DOMContentLoaded比load触发更早,不需要等图片等资源加载完成,布局稳定就执行
document.addEventListener('DOMContentLoaded', function() {
  // 计算元素到文档顶部的固定距离 = 相对视口距离 + 当前滚动高度
  const elembestellen = document.querySelector('#bestellen');
  const bestellen = elembestellen.getBoundingClientRect().top + window.scrollY;
  const eleminformatie = document.querySelector('#informatie');
  const informatie = eleminformatie.getBoundingClientRect().top + window.scrollY;
  const eleminspiratie = document.querySelector('#inspiratie');
  const inspiratie = eleminspiratie.getBoundingClientRect().top + window.scrollY;
  const elemreviews = document.querySelector('#reviews');
  const reviews = elemreviews.getBoundingClientRect().top + window.scrollY;

  $(window).scroll(function(){
    const w = Math.floor($(window).scrollTop());

    if(window.outerWidth > 767) {
      if(w > bestellen && w < informatie) {
        console.log('#bestellen reached');
      }
      if(w > informatie && w < inspiratie) {
        console.log('#informatie reached');
      }
      // 其余元素的判断逻辑可以按同样规则补充
    }
  });
});
可选优化建议

如果你的页面有动态内容加载、或者布局会动态变化的场景,可以把元素位置的计算逻辑抽到scroll事件里实时判断元素是否进入视口,适配性更强:

document.addEventListener('DOMContentLoaded', function() {
  $(window).scroll(function(){
    const w = Math.floor($(window).scrollTop());
    if(window.outerWidth <= 767) return;

    const bestellenTop = document.querySelector('#bestellen').getBoundingClientRect().top;
    const informatieTop = document.querySelector('#informatie').getBoundingClientRect().top;
    const inspiratieTop = document.querySelector('#inspiratie').getBoundingClientRect().top;

    // 元素顶部<=视口顶部 且 下一个元素还没进入视口,说明当前正处于该元素区域
    if(bestellenTop <= 0 && informatieTop > 0) {
      console.log('#bestellen reached');
    }
    if(informatieTop <=0 && inspiratieTop >0) {
      console.log('#informatie reached');
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:09:00