tt.createIntersectionObserver
基础库 1.10.4 开始支持本方法,低版本需做兼容处理。
创建并返回一个 IntersectionObserver 对象实例。在页面或自定义组件中,也可以使用 this.createIntersectionObserver([options])
来代替。
本方法创建并返回一个 IntersectionObserver
对象实例,使用方法类似于浏览器中的 Intersection Observer API
。
在小程序页面或自定义组件中,也可以使用 this.createIntersectionObserver([options])
来代替。
语法
tt.createIntersectionObserver(instance[, options])
参数说明
Page|Component
instance
页面实例或自定义组件实例。
Object options
可选参数,属性如下:
属性名 | 类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
---|---|---|---|---|---|
thresholds | number[] | [0] | 否 | 一个数值数组,包含所有阈值 | 1.10.4 |
initialRatio | number | 0 | 否 | 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数 | 1.10.4 |
observeAll | boolean | false | 否 | 是否同时观测多个目标节点(而非一个),如果设为 true ,observe 的 targetSelector 将选中多个节点(注意:同时选中过多节点将影响渲染性能) | 1.10.4 |
返回值
IntersectionObserver
对象实例。
扫码体验
请使用字节宿主APP扫码
代码示例
TTML
<scroll-view id="sv" scroll-y style="background:#eee; height: 300px">
<view id="target" style="margin:300px auto; width: 150px; height: 150px; background: lightblue;">
</view>
</scroll-view>
JavaScript
this.intersectionObserver = tt.createIntersectionObserver(this, {
thresholds: [0],
initialRatio: 0,
observeAll: false,
});
this.intersectionObserver.relativeTo("#sv");
// 当 #target 节点进入或离开 #sv 节点的可视区域时,则会触发回调函数
this.intersectionObserver.observe("#target", function (res) {
// 利用相交比例和各种边界信息实现业务逻辑,例如:判断目标元素是否进入屏幕可视范围等等
const { intersectionRatio, intersectionRect, boundingClientRect, relativeRect } = res;
});
点击纠错
评价此篇文档