Range: getBoundingClientRect() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

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

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
getBoundingClientRect

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報