ResizeObserverEntry: contentRect プロパティ

Baseline Widely available

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

contentRectResizeObserverEntry インターフェイスの読み取り専用プロパティで、コールバックが実行されたときに DOMRectReadOnly オブジェクトの形で監視中の要素の新しい寸法を返します。なお、これは ResizeObserverEntry.borderBoxSizeResizeObserverEntry.contentBoxSize よりも広く対応されていますが、 Resize Observer API では早期に除外され、現在は互換性の目的で仕様書に存在しているため、将来のバージョンでは非推奨になる可能性があります。

DOMRectReadOnly オブジェクトで、 target プロパティで示された要素の新しい寸法が入ります。

target が HTML の Element である場合、返される contentRect は要素のコンテンツボックスです。 targetSVGElement である場合、返される contentRect は SVG のバウンディングボックスです。

以下のスニペットは resize-observer-text.html (ソースを参照) の例から取ったものです。これは簡単な機能検出テストを使用して、ブラウザーがより新しい ResizeObserverEntry.contentBoxSize プロパティに対応しているかどうかを確認します。 — もし対応していれば、こちらを使用して必要な寸法のデータを取得します。そうでない場合は、 contentRect を使用します。

js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      h1Elem.style.fontSize = `${Math.max(
        1.5,
        entry.contentBoxSize.inlineSize / 200,
      )}rem`;
      pElem.style.fontSize = `${Math.max(
        1,
        entry.contentBoxSize.inlineSize / 600,
      )}rem`;
    } else {
      h1Elem.style.fontSize = `${Math.max(
        1.5,
        entry.contentRect.width / 200,
      )}rem`;
      pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`;
    }
  }
});

resizeObserver.observe(divElem);

仕様書

Specification
Resize Observer
# dom-resizeobserverentry-contentrect

ブラウザーの互換性

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
contentRect

Legend

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

Full support
Full support