Range: getBoundingClientRect() メソッド

Range.getBoundingClientRect() メソッドは、範囲のコンテンツを囲む DOMRect オブジェクトを返します。これは、範囲内のすべての要素の外接長方形の和を囲む長方形です。

このメソッドは、テキストボックス内のカーソルまたは選択範囲のビューポート座標を決定するのに有益です。返値の詳細については Element.getBoundingClientRect() を参照してください。

構文

js
getBoundingClientRect()

引数

なし。

返値

範囲内のすべての要素の外接長方形の和を囲む DOMRect オブジェクトです。

HTML

html
<div id="highlight"></div>
<p>
  この例では、範囲のコンテンツの後ろに「ハイライト」長方形を配置しています。
  範囲のコンテンツは<em>ここから始まり</em><em>ここで終わり</em>まで続きます。外接クライアント長方形は、範囲内で選択されたすべてのものを格納します。
</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`;

結果

仕様書

Specification
CSSOM View Module
# dom-range-getboundingclientrect

ブラウザーの互換性

BCD tables only load in the browser

関連情報