ResizeObserver: observe() 方法

Baseline 已廣泛支援

此特性已經十分成熟,可在許多裝置和瀏覽器版本上使用。自 2020 年 7 月以來,它已在各大瀏覽器中可用。

ResizeObserver 介面的 observe() 方法開始觀察指定的 ElementSVGElement

語法

js
observe(target)
observe(target, options)

引數

目標

要觀察的 ElementSVGElement 的引用。

options 可選

一個選項物件,允許你設定觀察選項。目前它只有一個可以設定的選項

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) {
      // Checking for chrome as using a non-standard array
      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("Size changed");
});

resizeObserver.observe(divElem);

使用選項物件的 observe() 呼叫示例如下所示

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

規範

規範
Resize Observer(調整大小觀察器)
# dom-resizeobserver-observe

瀏覽器相容性