blob: 9e5a3a577ad1deecb790d4afb8f6b1dbd3b4216b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
---
title: IntersectionObserver.observe()
slug: Web/API/IntersectionObserver/observe
translation_of: Web/API/IntersectionObserver/observe
---
<div>{{APIRef("Intersection Observer API")}}{{SeeCompatTable}}</div>
<p><span class="seoSummary">{{domxref("IntersectionObserver")}} 对象的<code><strong>observe()</strong></code> 方法向IntersectionObserver对象监听的目标集合添加一个元素。一个监听者有一组阈值和一个根, 但是可以监视多个目标元素,以查看这些目标元素可见区域的变化。</span>调用{{domxref("IntersectionObserver.unobserve()")}}方法可以停止观察元素。</p>
<p>当指定元素的可见区域超过监听者的可见区域阈值之一时(阈值列表{{domxref("IntersectionObserver.thresholds")}}),监听者的回调会被传入代表当前发生的交叉变化{{domxref("IntersectionObserverEntry")}}并执行。请注意,这种设计允许通过调用一次回调,给回调传入IntersectionObserverEntry对象数组,来实现同时处理多个被监听元素的交叉变化。</p>
<h2 id="语法">语法</h2>
<pre
class="brush: js"><em>IntersectionObserver</em>.observe(<em>targetElement</em>);</pre>
<h3 id="参数">参数</h3>
<dl>
<dt><code>targetElement</code></dt>
<dd>可见性区域被监控的元素{{domxref("element")}}。<br>
此元素必须是根元素的后代 (如果根元素为视窗,则该元素必须被当前文档包含)。</dd>
</dl>
<h3 id="返回值">返回值</h3>
<p><code>undefined</code>.</p>
<h2 id="Examples">示例</h2>
<pre class="brush: js">
// Register IntersectionObserver
const io = new IntersectionObserver(entries => {
entries.forEach(entry => {
// Add 'active' class if observation target is inside viewport
if (entry.intersectionRatio > 0) {
entry.target.classList.add('active');
}
// Remove 'active' class otherwise
else {
entry.target.classList.remove('active');
}
})
})
// Declares what to observe, and observes its properties.
const boxElList = document.querySelectorAll('.box');
boxElList.forEach((el) => {
io.observe(el);
})
</pre>
<h2 id="Specifications">规范</h2>
{{Specifications}}
<h2 id="Browser_compatibility">浏览器兼容性</h2>
<p>{{Compat}}</p>
<h2 id="See_also">参考</h2>
<ul>
<li>{{domxref("IntersectionObserver.unobserve()")}}</li>
</ul>
|