微信小程序中如何监听元素进入目标元素

javascript 复制代码
Page({
  onLoad: function(){
    // 如果目标节点(用选择器 .target-class 指定)进入显示区域以下 100px 时,就会触发回调函数。
    wx.createIntersectionObserver().relativeToViewport({bottom: 100}).observe('.target-class', (res) => {
      res.intersectionRatio // 相交区域占目标节点的布局区域的比例
      res.intersectionRect // 相交区域
      res.intersectionRect.left // 相交区域的左边界坐标
      res.intersectionRect.top // 相交区域的上边界坐标
      res.intersectionRect.width // 相交区域的宽度
      res.intersectionRect.height // 相交区域的高度
    })
  }
})

上面是相当于视口的,如何相当于目标元素视口:

使用relativeTo。

javascript 复制代码
<view class="container">
  <view class="page-body">
    <view class="page-section message">
      <text wx:if="{{appear}}">
        小球出现
      </text>
      <text wx:else>
        小球消失
      </text>
    </view>
    <view class="page-section">
      <scroll-view class="scroll-view" scroll-y>
        <view class="scroll-area" style="{{appear ? 'background: #ccc' : ''}}">
          <text class="notice">向下滚动让小球出现</text>
          <view class="filling"></view>
          <view class="ball"></view>
        </view>
      </scroll-view>
    </view>
  </view>
</view>
javascript 复制代码
Page({
  data: {
    appear: false
  },
  onLoad() {
    this._observer = wx.createIntersectionObserver(this)
    this._observer
      .relativeTo('.scroll-view')
      .observe('.ball', (res) => {
        console.log(res);
        this.setData({
          appear: res.intersectionRatio > 0
        })
      })
  },
  onUnload() {
    if (this._observer) this._observer.disconnect()
  }
})

小球与目标元素刚一交叉就出现。

继续滑动小球会消失

相关推荐
const_qiu2 小时前
微信小程序自动化测试100%通过率实践
微信小程序·小程序
Greg_Zhong6 小时前
小程序中登出/切换/重置页面状态的使用
小程序
一字白首6 小时前
微信小程序进阶实战:从 UI 组件库到全局状态管理全解DAY05
ui·微信小程序·小程序
海石20 小时前
微信小程序开发02:原始人也能看懂的着色器与视频处理
前端·微信小程序·视频编码
li9056632801 天前
hanzi-writer-miniprogram Path2D问题以及Bug修复
微信小程序·bug
土土哥V_araolin1 天前
双迪大健康新零售系统开发要点
小程序·个人开发·零售
2501_915909061 天前
不用越狱就看不到 iOS App 内部文件?使用 Keymob 查看和导出应用数据目录
android·ios·小程序·https·uni-app·iphone·webview
CHU7290351 天前
扭蛋机盲盒小程序前端功能设计及核心玩法介绍
前端·小程序
职豚求职小程序1 天前
中华财险笔试测评题库小程序刷题职豚2026新
小程序
阿珊和她的猫1 天前
小程序双线程架构:逻辑层与视图层的协同运作机制
小程序·架构