DHTML: Range.getBoundingClientRect メソッド  編集:2021.12.12 by T.A.

範囲の内容を制限する DOMRect オブジェクトを返します。→MS(en)

実験的: これは実験的技術です。これを本番環境で使用する前に、ブラウザの互換性テーブルを注意深く確認してください。

これは、範囲内のすべての要素の外接する長方形の結合を囲む長方形です。

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

boundingRect = range.getBoundingClientRect()
range
Range
boundingRect
戻り値DOMRect オブジェクト。

HTML:

<div id="highlight"></div>
<p>This example positions a "highlight" rectangle behind the contents of a range. The range's content <b>starts here</b> and continues on until it <b>ends here</b>. The bounding client rectangle contains everything selected in the range.</p>

CSS:

#highlight {
  background: yellow;
  position: absolute;
  z-index: -1;
}

p {
  width: 200px;
}

JavaScript:

const range = document.createRange();
range.setStartBefore(document.getElementsByTagName('b').item(0), 0);
range.setEndAfter(document.getElementsByTagName('b').item(1), 0);

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`;

テスト
HTML:

ここに表示
スクリプト:


スクリプト:



表示内容:
表示内容: