- JS API 列表
- 基础
- 网络
- 媒体
- 地图
- 文件
- 开放接口
- 数据缓存
- 地理位置
- 设备
- 画布
- 界面
- 页面导航
- 侧边栏能力
- 行业开放
- AI/AR能力
- 第三方平台
- TTML
- 转发和挂载
- 其它
- 直播能力
tt.createIntersectionObserver收藏我的收藏
收藏
我的收藏基础库 1.10.4 开始支持本方法,这是一个同步方法。
在小程序页面或自定义组件中,也可以使用
this.createIntersectionObserver(options)
来代替。语法
text复制tt.createIntersectionObserver(instance, options)
参数说明
instance
类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
Page | Comonent | | 是 | 页面实例或自 定义组件实例 | 1.10.4 |
options
类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
Options | | 否 | 配置项 | 1.10.4 |
Options 类型说明
object 类型,属性如下:
属性 | 类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
thresholds | number[] | [0] | 否 | 一个数值数组,包含所有阈值 | 1.10.4 |
initialRatio | number | 0 | 否 | 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数 | 1.10.4 |
observeAll | boolean | false | 否 | 是否同时观测多个目标节点(而非一个),如果设为 true ,observe 的 targetSelector 将选中多个节点(注意:同时选中过多节点将影响渲染性能) | 1.10.4 |
返回值
扫码体验
代码示例
html复制<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>
js复制//【示例一】
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;
});
//【示例二】利用IntersectionObserver上报 FMP
onReady() {
const intersectionObserver = tt.createIntersectionObserver(this, {
thresholds: [0],
initialRatio: 0,
observeAll: false,
});
// 假设 #container 为页面根节点
intersectionObserver.relativeTo("#container");
// 假设 #main-content 为产品首屏中的主要内容
intersectionObserver.observe("#main-content", (res) => {
tt.performance.mark("FMP");
intersectionObserver.disconnect();
});
}
Bug & Tip
- •Tip:利用 IntersectionObserver 上报 FMP;我们可以认为页面主要内容出现在页面根节点上时,就是 FMP 的时间,详见代码示例-示例二。
点击纠错