小程序 IntersectionObserver 使用案例
今天聊聊小程序的 IntersectionObserver
接口。
兼容性
基础信息:
- 文档: IntersectionObserver
- 兼容: 基础库 > 1.9.3
observeAll
: 基础库 > 2.0.0
API
通过 IntersectionObserver wx.createIntersectionObserver(Object this, Object options)
创建 IntersectionObserver
对象实例 options
可选配置有
thresholds
,触发阈值的集合数组,默认[0]
,例:我配置了[0, 0.5, 0.8]
,那么当监听对象和参照物相交比例达到0 / 0.5 / 0.8
时,会触发监听器的回调函数initialRatio
,初始相交比例,默认0
,达到initialRatio
或thresholds
中的阈值时,回调被触发observeAll
,是否同时监听多个对象,默认false
,下文的列表埋点会用到(⚠️:基础库 > 2.0.0)
接下来看下 IntersectionObserver
的方法,
disconnect
,停止监听.observe(string targetSelector, function callback)
,指定监听对象,并且设置回调函数
intersectionRatio
,这个数据很关键,相交比例,用作临界判断的指标intersectionRect
Object{left、right、top、bottom},相交区域的边界boundingClientRect
Object{left、right、top、bottom},目标边界relativeRect
Object{left、right、top、bottom},参照区域的边界time
number 相交检测时的时间戳
.relativeTo(string selector, Object margins)
,通过选择器指定一个节点作为参照区域之一,而margins
包括left / right / top / bottom
可以设置与某一边界的达到一定距离时触发回调.relativeToViewport(Object margins)
,指定页面显示区域作为参照区域之一
案例
多数 onScroll
的应用场景都可以被 IntersectionObserver
取代,这里举两个案例。
列表数据监控
场景:商品列表场景下,统计用户访问到第多少个商品离开页面,甚至上报已经看到的商品列表,在这个场景里,需要监听多个对象,并且在列表数据增加时,监听的对象也需要更新
1 | interSection: function (e) { |
吸顶效果
小程序无法使用 sticky
,我们会通过 scroll-view
的 bindscroll
来实现吸顶效果,但是 bindscroll
实际使用体验并不是很好,不过可以用 IntersectionObserver
来实现。
1 | <view class="filter-container"> |
1 | filterInterSection: function(e) { |
作者: leeon
来源: https://leeon.im
链接: https://leeon.im/mp-IntersectionObserver/
本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可