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

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

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

继续滑动小球会消失

相关推荐
2501_9160074714 小时前
苹果手机iOS应用管理全指南与隐藏功能详解
android·ios·智能手机·小程序·uni-app·iphone·webview
Gracemark15 小时前
H5回调页开发与调试复盘
微信小程序
yogalin199316 小时前
微信小程序代码复用技巧
性能优化·微信小程序
求学中--16 小时前
进阶实战:构建一个完整的微信小程序博客系统(含云开发与状态管理)
微信小程序·小程序
2501_9151063217 小时前
全面理解 iOS 帧率,构建从渲染到系统行为的多工具协同流畅度分析体系
android·ios·小程序·https·uni-app·iphone·webview
计算机毕设指导619 小时前
基于微信小程序的宠物走失信息管理系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·宠物
2501_9160088919 小时前
iOS 能耗检测的工程化方法,构建多工具协同的电量分析与性能能效体系
android·ios·小程序·https·uni-app·iphone·webview
说私域19 小时前
基于开源链动2+1模式AI智能名片S2B2C商城小程序的线上向线下导流运营研究
人工智能·小程序·开源
小小王app小程序开发19 小时前
任务悬赏小程序核心玩法 + 功能全解析:精准匹配与信任构建的变现逻辑
大数据·小程序
头发还在的女程序员19 小时前
陪诊小程序成品|陪诊系统功能|陪诊系统功能(源码)
java·小程序·his系统