Range:getClientRects() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Range.getClientRects() 方法返回一個 DOMRect 物件列表,表示 range 在螢幕上佔用的區域。這是透過聚合範圍中所有元素的 Element.getClientRects() 呼叫結果而建立的。

語法

js
getClientRects()

引數

無。

返回值

一個 iterable 序列的 DOMRect 物件。

示例

記錄選定的客戶端矩形大小

HTML

html
<div></div>
<pre id="output"></pre>

CSS

css
div {
  height: 80px;
  width: 200px;
  background-color: blue;
}

JavaScript

js
const range = document.createRange();
range.selectNode(document.querySelector("div"));
rectList = range.getClientRects();

const output = document.querySelector("#output");
for (const rect of rectList) {
  output.textContent = `${output.textContent}\n${rect.width}:${rect.height}`;
}

結果

規範

規範
CSSOM 檢視模組
# dom-range-getclientrects

瀏覽器相容性

另見