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

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

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

继续滑动小球会消失

相关推荐
游戏开发爱好者82 小时前
FTP 抓包分析实战,命令、被动主动模式要点、FTPS 与 SFTP 区别及真机取证流程
运维·服务器·网络·ios·小程序·uni-app·iphone
努力就够了2 小时前
微信小程序:日常零售供应系统
微信小程序·erp·接单·零售系统
说私域2 小时前
基于开源AI大模型、AI智能名片与S2B2C商城小程序的购物中心精准零售数据架构研究
人工智能·小程序·开源
说私域3 小时前
开源链动2+1模式、AI智能名片与S2B2C商城小程序:社群经济的数字化重构路径
人工智能·小程序·开源
peachSoda73 小时前
封装一个不同跳转方式的通用方法(跳转外部链接,跳转其他小程序,跳转半屏小程序)
前端·javascript·微信小程序·小程序
2501_915909064 小时前
iOS 26 文件管理实战,多工具组合下的 App 数据访问与系统日志调试方案
android·ios·小程序·https·uni-app·iphone·webview
云起SAAS5 小时前
ai周公解梦抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·ai周公解梦
Jing_jing_X7 小时前
微信小程序开发踩坑记:从AI工具翻车到找到合适方案
人工智能·ai·小程序·产品运营·个人开发
一匹电信狗8 小时前
【MySQL】数据库的相关操作
linux·运维·服务器·数据库·mysql·ubuntu·小程序
weixin_lynhgworld12 小时前
旧物新生,从二手回收小程序开启绿色生活
小程序·生活·旧物回收