aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/resizeobserver/index.html
blob: 602fb4b35141bbd8ec3dfef051fc04bf7dd69035 (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
68
69
70
71
72
73
74
75
76
77
78
79
---
title: ResizeObserver
slug: Web/API/ResizeObserver
translation_of: Web/API/ResizeObserver
---
<div>{{APIRef("Resize Observer API")}}{{SeeCompatTable}}</div>

<p class="summary"><strong><code>ResizeObserver</code></strong> 接口可以监听到 {{domxref('Element')}} 的内容区域或 {{domxref('SVGElement')}}的边界框改变。内容区域则需要减去内边距padding。(有关内容区域、内边距资料见<a href="https://developer.mozilla.org/docs/Learn/CSS/Introduction_to_CSS/Box_model">盒子模型</a></p>

<p>ResizeObserver避免了在自身回调中调整大小,从而触发的无限回调和循环依赖。它仅通过在后续帧中处理DOM中更深层次的元素来实现这一点。如果(浏览器)遵循规范,只会在绘制前或布局后触发调用。</p>

<h2 id="构造器">构造器</h2>

<dl>
 <dt>{{domxref("ResizeObserver.ResizeObserver", "ResizeObserver()")}}</dt>
 <dd>创建并返回一个<code>ResizeObserver</code>对象。</dd>
</dl>

<h2 id="属性">属性</h2>

<p>无。</p>

<h3 id="Event_handlers">Event handlers</h3>

<p>无。</p>

<h2 id="方法">方法</h2>

<dl>
 <dt>{{domxref('ResizeObserver.disconnect()')}}</dt>
 <dd>取消和结束目标对象上所有对 {{domxref('Element')}}{{domxref('SVGElement')}} 观察。</dd>
 <dt>{{domxref('ResizeObserver.observe()')}}</dt>
 <dd>开始观察指定的 {{domxref('Element')}}{{domxref('SVGElement')}}</dd>
 <dt>{{domxref('ResizeObserver.unobserve()')}}</dt>
 <dd>结束观察指定的{{domxref('Element')}}{{domxref('SVGElement')}}</dd>
</dl>

<h2 id="示例">示例</h2>

<p>以下示例通过观察box的宽度变化从而改变其边框圆角半径。</p>

<pre class="brush: js">const resizeObserver = new ResizeObserver(entries =&gt; {
  for (let entry of entries) {
    entry.target.style.borderRadius = Math.max(0, 250 - entry.contentRect.width) + 'px';
  }
});
resizeObserver.observe(document.querySelector('.box:nth-child(2)'));</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('Resize Observer','#resize-observer-interface','ResizeObserver')}}</td>
   <td>{{Spec2('Resize Observer')}}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>



<p>{{Compat("api.ResizeObserver")}}</p>

<h2 id="参考">参考</h2>

<ul>
 <li><a href="https://developer.mozilla.org/docs/Learn/CSS/Introduction_to_CSS/Box_model">The box model</a></li>
 <li>{{domxref('PerformanceObserver')}}</li>
 <li>{{domxref('MutationObserver')}}</li>
 <li>{{domxref('IntersectionObserver')}} (part of the <a href="/en-US/docs/Web/API/Intersection_Observer_API">Intersection Observer API</a>)</li>
</ul>