今天聊聊小程序的 IntersectionObserver 接口。

兼容性

基础信息:

API

通过 IntersectionObserver wx.createIntersectionObserver(Object this, Object options) 创建 IntersectionObserver 对象实例 options 可选配置有

  • thresholds,触发阈值的集合数组,默认 [0],例:我配置了 [0, 0.5, 0.8],那么当监听对象和参照物相交比例达到 0 / 0.5 / 0.8 时,会触发监听器的回调函数
  • initialRatio,初始相交比例,默认 0,达到 initialRatiothresholds 中的阈值时,回调被触发
  • observeAll,是否同时监听多个对象,默认 false,下文的列表埋点会用到(⚠️:基础库 > 2.0.0)

接下来看下 IntersectionObserver 的方法,

  1. disconnect,停止监听

  2. .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 相交检测时的时间戳
  1. .relativeTo(string selector, Object margins),通过选择器指定一个节点作为参照区域之一,而 margins 包括 left / right / top / bottom 可以设置与某一边界的达到一定距离时触发回调

  2. .relativeToViewport(Object margins),指定页面显示区域作为参照区域之一

案例

多数 onScroll 的应用场景都可以被 IntersectionObserver 取代,这里举两个案例。

列表数据监控

场景:商品列表场景下,统计用户访问到第多少个商品离开页面,甚至上报已经看到的商品列表,在这个场景里,需要监听多个对象,并且在列表数据增加时,监听的对象也需要更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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-viewbindscroll 来实现吸顶效果,但是 bindscroll 实际使用体验并不是很好,不过可以用 IntersectionObserver 来实现。

1
2
3
<view class="filter-container">
<filter class="{{isFixed ? 'fixed' : ''}}" />
</view>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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()
}
}