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

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()
  }
})

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

继续滑动小球会消失

相关推荐
职豚求职小程序2 小时前
中国人保财险笔试如何通过?附刷题库小程序
小程序
chushiyunen2 小时前
python轻量级框架flask、做桌面小程序
python·小程序·flask
笨笨狗吞噬者3 小时前
【uniapp】小程序支持分包存放微信自定义组件 wxcomponents
前端·微信小程序·uni-app
蓝色心灵-海4 小时前
小律书 技术架构详解:前后端分离的自律管理系统设计
java·http·小程序·架构·uni-app
00后程序员张6 小时前
iPhone 无需越狱文件管理 使用Keymob查看导出文件
android·ios·小程序·https·uni-app·iphone·webview
毕设源码-朱学姐6 小时前
【开题答辩全过程】以 基于微信小程序的运动减肥管理系统设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
2501_916008896 小时前
Unity3D iOS 应用防篡改实战 资源校验、 IPA 二进制保护
android·ios·小程序·https·uni-app·iphone·webview
2501_915909066 小时前
MachObfuscator全面解析:Apple平台Mach-O应用程序混淆技术指南
macos·ios·小程序·uni-app·objective-c·cocoa·iphone
大鹏说大话8 小时前
微信小程序制作一个需要多少钱?
微信小程序
2501_9159184120 小时前
苹果App Store上架审核卡住原因分析与解决方案指南
android·ios·小程序·https·uni-app·iphone·webview