Skip to main content
Version: 3.x

IntersectionObserver

IntersectionObserver 对象,用于推断某些节点是否可以被用户看见、有多大比例可以被用户看见。

参考文档

方法#

disconnect#

停止监听。回调函数将不再触发

参考文档

() => void

observe#

指定目标节点并开始监听相交状态变化情况

参考文档

(targetSelector: string, callback: ObserveCallback) => void
参数类型说明
targetSelectorstring选择器
callbackObserveCallback监听相交状态变化的回调函数

relativeTo#

使用选择器指定一个节点,作为参照区域之一。

参考文档

(selector: string, margins?: RelativeToMargins) => IntersectionObserver
参数类型说明
selectorstring选择器
marginsRelativeToMargins用来扩展(或收缩)参照节点布局区域的边界

relativeToViewport#

指定页面显示区域作为参照区域之一

参考文档

(margins?: RelativeToViewportMargins) => IntersectionObserver
参数类型说明
marginsRelativeToViewportMargins用来扩展(或收缩)参照节点布局区域的边界

示例代码#

下面的示例代码中,如果目标节点(用选择器 .target-class 指定)进入显示区域以下 100px 时,就会触发回调函数。

Taro.createIntersectionObserver().relativeToViewport({bottom: 100}).observe('.target-class', (res) => {
res.intersectionRatio // 相交区域占目标节点的布局区域的比例
res.intersectionRect // 相交区域
res.intersectionRect.left // 相交区域的左边界坐标
res.intersectionRect.top // 相交区域的上边界坐标
res.intersectionRect.width // 相交区域的宽度
res.intersectionRect.height // 相交区域的高度
})

参数#

ObserveCallback#

监听相交状态变化的回调函数

(result: ObserveCallbackResult) => void
参数类型
resultObserveCallbackResult

ObserveCallbackResult#

参数类型说明
boundingClientRectBoundingClientRectResult目标边界
intersectionRationumber相交比例
intersectionRectIntersectionRectResult相交区域的边界
relativeRectRelativeRectResult参照区域的边界
timenumber相交检测时的时间戳

RelativeRectResult#

参照区域的边界

参数类型说明
bottomnumber下边界
leftnumber左边界
rightnumber右边界
topnumber上边界

IntersectionRectResult#

相交区域的边界

参数类型说明
bottomnumber下边界
heightnumber高度
leftnumber左边界
rightnumber右边界
topnumber上边界
widthnumber宽度

BoundingClientRectResult#

目标边界

参数类型说明
bottomnumber下边界
heightnumber高度
leftnumber左边界
rightnumber右边界
topnumber上边界
widthnumber宽度

RelativeToMargins#

用来扩展(或收缩)参照节点布局区域的边界

参数类型必填说明
bottomnumber节点布局区域的下边界
leftnumber节点布局区域的左边界
rightnumber节点布局区域的右边界
topnumber节点布局区域的上边界

RelativeToViewportMargins#

用来扩展(或收缩)参照节点布局区域的边界

参数类型必填说明
bottomnumber节点布局区域的下边界
leftnumber节点布局区域的左边界
rightnumber节点布局区域的右边界
topnumber节点布局区域的上边界