跳至主内容

IntersectionObserver 🧪

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

Canary 🧪

此 API 当前仅在 React Native 的 Canary 和 Experimental 频道中可用。

如果你想试用,请在你的应用中启用 Canary 频道

全局 IntersectionObserver 接口,遵循 Web 规范定义。它提供了一种异步观察目标元素与祖先元素或顶级文档视口交叉状态变化的方法。


参考

构造函数

IntersectionObserver()

参阅 MDN 文档

创建一个新的 IntersectionObserver 对象,当检测到目标元素的可见性超过一个或多个 thresholdrnRootThreshold 值时,将执行指定的回调函数。

ts
new IntersectionObserver(callback, options?)

参数

callback

当目标元素可见比例超过阈值时调用的函数。该回调接收两个参数:

  • entries:由 IntersectionObserverEntry 对象组成的数组,每个对象代表一个被跨越的阈值,表示目标元素变得比该阈值指定的比例更可见或更不可见。

  • observer:调用该回调的 IntersectionObserver 实例。

options(可选)

包含以下属性的可选对象:

NameTypeDescription
rootElement | nullAn element that is an ancestor of the target, whose bounding rectangle will be considered the viewport. Defaults to the root viewport if not specified or if null.
rootMarginstringA string which specifies a set of offsets to add to the root's bounding box when calculating intersections. Defaults to "0px 0px 0px 0px".
thresholdnumber | number[]Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target. Defaults to [0] if rnRootThreshold is not set.
rnRootThreshold ⚠️number | number[]React Native specific. Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to the total root area.

实例属性

root

参阅 MDN 文档

在检测交叉状态时,用作边界框的元素或文档。

rootMargin

参阅 MDN 文档

计算交叉状态时应用于根元素边界框的偏移矩形。

rnRootThresholds ⚠️

非标准

此为 React Native 特有的扩展。

按数值升序排列的根阈值列表,每个阈值表示目标元素与指定根视图(默认为视口)边界框区域的交叉面积比例。

当目标元素的 rnRootThresholdsthresholds 中任一阈值被跨越时,将生成通知。

ts
get rnRootThresholds(): ReadonlyArray<number> | null;

thresholds

参阅 MDN 文档

按数值升序排列的阈值列表,每个阈值表示被观察目标元素自身边界框区域的交叉面积比例。

当目标元素的 rnRootThresholdsthresholds 中任一阈值被跨越时,将生成通知。

实例方法

disconnect()

参阅 MDN 文档

停止 IntersectionObserver 对象观察所有目标。

observe()

参阅 MDN 文档

指示 IntersectionObserver 开始观察目标元素。

takeRecords()

参阅 MDN 文档

返回所有被观察目标的 IntersectionObserverEntry 对象数组。

unobserve()

请参阅 MDN 中的文档

告知 IntersectionObserver 停止观察特定的目标元素。