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

瀏覽器相容性

另見