Range:getBoundingClientRect() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Range.getBoundingClientRect() 方法返回一个 DOMRect 对象,该对象包围了 range 中的内容;这是一个包围 range 中所有元素的边界矩形的并集的矩形。

此方法对于确定文本框内光标或选区的视口坐标非常有用。有关返回值的详细信息,请参阅 Element.getBoundingClientRect()

语法

js
getBoundingClientRect()

参数

无。

返回值

一个 DOMRect 对象,它包围了 range 中所有元素的边界矩形的并集。

示例

HTML

html
<div id="highlight"></div>
<p>
  This example positions a "highlight" rectangle behind the contents of a range.
  The range's content <em>starts here</em> and continues on until it
  <em>ends here</em>. The bounding client rectangle contains everything selected
  in the range.
</p>

CSS

css
#highlight {
  background: yellow;
  position: absolute;
  z-index: -1;
}

p {
  width: 200px;
}

JavaScript

js
const range = document.createRange();
range.setStartBefore(document.getElementsByTagName("em").item(0));
range.setEndAfter(document.getElementsByTagName("em").item(1));

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`;

结果

规范

规范
CSSOM 视图模块
# dom-range-getboundingclientrect

浏览器兼容性

另见