在小程序内监听元素是否可见

小程序 IntersectionObserver API 文档

例如下方的代码:

IntersectionObserver
1
2
3
4
5
6
7
8
9
10
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; // 相交区域的高度
});

通过 wx.createIntersectionObserver(Object component, Object options)创建一个观察对象,再通过这个观察对象的 relativeToViewport 方法对指定的一个 dom 元素进行视窗的相交比对,我们可以得到这个 dom 元素和视窗的相交比例、相较区域、相交区域的坐标、宽度和高度。

intersectionRatio 的返回结果为 0 或 1,当 intersectionRatio === 0 时,表示这个 dom 元素和视窗完全不相交,为 1 则表示这个 dom 元素和视窗相交,即这个 dom 元素当前可见。

示例代码片段,点击查看

预览效果

延伸的应用:通过监听元素是否可见,可以实现比如 sticky 粘性布局、无限加载等需求。

完结,撒花

在小程序内监听元素是否可见

https://lynan.cn/observe-element-visibility-in-mp/

Author

Lynan

Posted on

2020-10-28

Licensed under