ResizeObserver: observe() メソッド

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.

observe()ResizeObserver インターフェイスのメソッドで、指定された Element または SVGElement の監視を開始します。

構文

js
observe(target)
observe(target, options)

引数

target

監視する Element または SVGElement への参照。

options 省略可

監視のオプションを設定することができるオプションオブジェクトです。現在、設定可能なオプションは 1 つだけです。

box

オブザーバーがどのボックスモデルの変更を観察するかを設定します。設定可能な値は以下の通りです。

content-box (既定値)

CSS で定義されたコンテンツ領域のサイズ。

border-box

CSS で定義されたボックス境界領域のサイズ。

device-pixel-content-box

CSS で定義されたコンテンツ領域の大きさ。デバイスピクセル単位で、要素またはその祖先に対して CSS 変換を適用する前の値。

返値

なし (undefined)。

例外

なし。

次のスニペットは resize-observer-text.html (ソースを表示) の例から取ったものです。

js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      // クロームが標準外の配列を使用しているかどうかのチェック
      if (entry.contentBoxSize[0]) {
        h1Elem.style.fontSize = `${Math.max(
          1.5,
          entry.contentBoxSize[0].inlineSize / 200,
        )}rem`;
        pElem.style.fontSize = `${Math.max(
          1,
          entry.contentBoxSize[0].inlineSize / 600,
        )}rem`;
      } else {
        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`;
    }
  }
  console.log("サイズが変更されました");
});

resizeObserver.observe(divElem);

オプションオブジェクトを使った observe() の呼び出しは、次のようになります。

js
resizeObserver.observe(divElem, { box: "border-box" });

仕様書

Specification
Resize Observer
# dom-resizeobserver-observe

ブラウザーの互換性

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
observe
options.box parameter

Legend

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

Full support
Full support
See implementation notes.