aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/range/getboundingclientrect/index.html
blob: d49eb8c65c2af255894a1b4b583e9b1a3866e1d5 (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
---
title: Range.getBoundingClientRect()
slug: Web/API/Range/getBoundingClientRect
tags:
  - API
  - CSSOM View
  - Method
  - Range
  - 域
  - 方法
  - 范围
translation_of: Web/API/Range/getBoundingClientRect
---
<div>{{ApiRef("DOM")}}{{SeeCompatTable}}</div>

<p><strong><code>Range.getBoundingClientRect()</code></strong> 返回一个 {{ domxref("DOMRect") }} 对象,该对象将范围中的内容包围起来;即该对象是一个将范围内所有元素的边界矩形包围起来的矩形(译者注:关于边界矩形,可以参考 <a href="https://en.wikipedia.org/wiki/Minimum_bounding_rectangle">Minimum Bouding Rectangles</a>)。</p>

<p>此方法可用于确定文本区域中选中的部分或光标的视窗坐标。关于返回值的详细信息,参见 {{domxref("Element.getBoundingClientRect()")}}。</p>

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

<pre class="syntaxbox notranslate"><var>boundingRect</var> = <var>range</var>.getBoundingClientRect()
</pre>

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

<h3 id="HTML">HTML</h3>

<pre class="brush: html ">&lt;div id="highlight"&gt;&lt;/div&gt;
&lt;p&gt;This example positions a "highlight" rectangle behind the contents of a range. The range's content &lt;b&gt;starts here&lt;/b&gt; and continues on until it &lt;b&gt;ends here&lt;/b&gt;. The bounding client rectangle contains everything selected in the range.&lt;/p&gt;</pre>

<h3 id="CSS">CSS</h3>

<pre class="brush: css">#highlight {
  background: yellow;
  position: absolute;
  z-index: -1;
}

p {
  width: 200px;
}</pre>

<h3 id="JavaScript">JavaScript</h3>

<pre class="brush: js">const range = document.createRange();
range.setStartBefore(document.getElementsByTagName('b').item(0), 0);
range.setEndAfter(document.getElementsByTagName('b').item(1), 0);

const clientRect = range.getBoundingClientRect();
const highlight = document.getElementById('highlight');
highlight.style.left = `${clientRect.x}px`;
highlight.style.top = `${clientRect.y}px`;
highlight.style.width = `${clientRect.width}px`;
highlight.style.height = `${clientRect.height}px`;</pre>

<h3 id="结果">结果</h3>

<p>{{EmbedLiveSample("Example")}}</p>

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

{{Specifications}}

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

<p>{{Compat}}</p>

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

<ul>
 <li>{{domxref("Range.getClientRects()")}} - 对于非矩形的范围(如选择部分换行了)会返回更细致的结果。</li>
 <li>{{domxref("Element.getBoundingClientRect()")}}</li>
 <li>{{domxref("Document.caretPositionFromPoint()")}} - 使用视窗坐标获取节点范围。</li>
</ul>