大网数据广告活动
Web 标准与前端开发

ResizeObserver.observe()

· 52CE 我爱测

ResizeObserver 接口的 **`observe()`** 方法用于监听指定的 Element 或 SVGElement。

Resize Observer API

ResizeObserver 接口的 observe() 方法用于监听指定的 Element 或 SVGElement。

语法

observe(target)
observe(target, options)

参数

  • target
    • : 对要监听的 Element 或 SVGElement 的引用。
  • options
    • : 一个可选的对象,允许你为监听的对象设置参数。目前,这只有一个参数:
      • box
        • : 设置 observer 将监听的盒模型。可能的值是:
          • content-box(默认)
            • : CSS 中定义的内容区域的大小。
          • border-box
            • : CSS 中定义的边框区域的大小。
          • device-pixel-content-box
            • : 在对元素或其祖先应用任何 CSS 转换之前,CSS 中定义的内容区域的大小,以设备像素为单位。

返回值

无(undefined)。

异常

无。

示例

以下片段取自 resize-observer-text.html(见源码)示例:

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() 看起来像这样:

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

规范

浏览器兼容性

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。