Range:getBoundingClientRect() 方法
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 |
瀏覽器相容性
載入中…
另見
Range.getClientRects()- 為非矩形範圍提供更精細的結果(例如,當選區換行時);Element.getBoundingClientRect()Document.caretPositionFromPoint()- 從視口座標獲取(節點,偏移量)。