前端小盖的博客
欢迎来到前端小盖的博客

js 的滚动监听(react class)

关于滚动监听方案

方案一: IntersectionObserver 与视口的重叠度
查询其浏览器兼容性 https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver#浏览器兼容性

谷歌最低兼容51, 由于医院有使用49版本的浏览器,故该方案暂时舍弃, 后面维护

方案二: js onScroll监听

// 滚动底部阈值 px
this.threshold = 50;
this.reachBottomFlag = false; // 触底标识, 防止多次触发触底事件

const handleScroll = (e) => {
    const { scrollHeight, scrollTop } = e.target; // {滚动内容高度、滚动条顶部距离}
    const offsetHight = e.target.getBoundingClientRect().height; // 视口高度
    // 阈值高度 默认距底部50px触发
    const thresholdHeight = offsetHight + scrollTop + this.threshold;
    if (thresholdHeight < scrollHeight && this.reachBottomFlag) {
      this.reachBottomFlag = false; // 重置触底标识
    } else if (!this.reachBottomFlag && thresholdHeight >= scrollHeight) {
      this.reachBottomFlag = true; 
      // 触底回调...
    }
  }
posted @ 2025-05-27 10:33  前端小盖  阅读(38)  评论(0)    收藏  举报