本文共 2506 字,大约阅读时间需要 8 分钟。
今天聊聊小程序的 IntersectionObserver
接口。
基础信息:
- 文档:
- 兼容: 基础库 > 1.9.3
observeAll
: 基础库 > 2.0.0
通过 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
取代,这里举两个案例。
场景:商品列表场景下,统计用户访问到第多少个商品离开页面,甚至上报已经看到的商品列表,在这个场景里,需要监听多个对象,并且在列表数据增加时,监听的对象也需要更新
interSection: function (e) { if (this._observer) { this._observer.disconnect() } this._observer = this.createIntersectionObserver({ // 阈值设置少,避免触发过于频繁导致性能问题 thresholds: [1], // 监听多个对象 observeAll: true }) .relativeToViewport({ bottom: 0 }) .observe('.item', (item) => { let idx = item.dataset && item.dataset.idx // 获取浏览的最底部元素的 idx if (idx > this.data.expoIdx) { this.setData({ expoIdx: idx }) } })},getList: function() { // 列表数据更新后,重新绑定监听 this.setData({ list: newList }, this.interSection)},logViewCount: function () { // 上报数据 log(this.data.expoIdx)},onHide: function () { this.logViewCount()},onUnload() { if (this._observer) { // 解绑 this._observer.disconnect() }}
小程序无法使用 sticky
,我们会通过 scroll-view
的 bindscroll
来实现吸顶效果,但是 bindscroll
实际使用体验并不是很好,不过可以用 IntersectionObserver
来实现。
filterInterSection: function(e) { this.filterObserver = this.createIntersectionObserver({ thresholds: [0, 0.5, 1] }) .relativeToViewport() .observe('.filter-container', (data) => { if (data.intersectionRatio < 1) { this.setData({ isFixed: true }) } else { this.setData({ isFixed: false }) } })},onLoad: function (options) { this.filterInterSection()},onUnload() { if(this.filterInterSection) { this.filterInterSection.disconnect() }}
转载地址:http://oiod.baihongyu.com/