Range: getBoundingClientRect() Methode

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.

Die Range.getBoundingClientRect() Methode gibt ein DOMRect-Objekt zurück, das den Inhalt des Bereichs umfasst; dies ist ein Rechteck, das die Vereinigung der Begrenzungsrechtecke aller Elemente im Bereich umschließt.

Diese Methode ist nützlich, um die Ansichtskoordinaten des Cursors oder der Auswahl innerhalb eines Textfelds zu bestimmen. Siehe Element.getBoundingClientRect() für Details zum zurückgegebenen Wert.

Syntax

js
getBoundingClientRect()

Parameter

Keine.

Rückgabewert

Ein DOMRect-Objekt, das die Vereinigung der Begrenzungsrechtecke aller Elemente im Bereich umschließt.

Beispiele

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

Ergebnis

Spezifikationen

Specification
CSSOM View Module
# dom-range-getboundingclientrect

Browser-Kompatibilität

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

Siehe auch