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

如何使用Intersection Observer监听元素顶部和底部的进出视口事件

解决方案

核心修改点

你当前的配置threshold: 0代表仅当元素可见比例为0%的时候触发回调,也就是只有元素顶部刚进入/刚离开视口的节点会触发事件。要监听更多进出状态,只需要调整阈值配置,再结合元素位置信息做判断即可。

完整实现代码

// 用WeakMap存储每个被观测元素的上一次可见比例,区分进出状态
const prevIntersectionRatio = new WeakMap()

this.observer = new IntersectionObserver(
  (entries) => {
    entries.forEach((entry) => {
      const target = entry.target
      const prevRatio = prevIntersectionRatio.get(target) ?? 0
      const currentRatio = entry.intersectionRatio
      prevIntersectionRatio.set(target, currentRatio)

      const viewportHeight = window.innerHeight
      const elRect = entry.boundingClientRect

      // 元素底部进入视口
      if (elRect.bottom <= viewportHeight && currentRatio > 0 && prevRatio < 1) {
        console.log('元素底部进入视口')
      }

      // 元素完全进入视口
      if (currentRatio === 1 && prevRatio < 1) {
        console.log('元素完全进入视口')
      }

      // 元素底部离开视口
      if (elRect.bottom > viewportHeight && currentRatio < 1 && prevRatio >= 1) {
        console.log('元素底部离开视口')
      }

      // 元素完全离开视口
      if (currentRatio === 0 && prevRatio > 0) {
        console.log('元素完全离开视口')
      }
    })
  },
  {
    rootMargin: "0px 0px 0px",
    root: null,
    threshold: [0, 1], // 可见比例达到0%、100%时都触发回调
  }
);

补充说明

如果你的元素高度大于视口高度,元素永远不可能完全进入视口,threshold的1永远不会触发,这种情况可以按需调整阈值,比如设置threshold: [0, 0.5, 1]新增中间触发点,或者根据业务需求调整判断逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:09:01