此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Range.getBoundingClientRect()

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

Range.getBoundingClientRect() 返回一个 DOMRect 对象,该对象将范围中的内容包围起来;即该对象是一个将范围内所有元素的边界矩形包围起来的矩形(译者注:关于边界矩形,可以参考 Minimum Bouding Rectangles)。

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

语法

boundingRect = range.getBoundingClientRect()

示例

HTML

html
<div id="highlight"></div>
<p>
  This example positions a "highlight" rectangle behind the contents of a range.
  The range's content <b>starts here</b> and continues on until it
  <b>ends here</b>. 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("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`;

结果

规范

规范
CSSOM View Module
# dom-range-getboundingclientrect

浏览器兼容性

参见