ResizeObserverEntry

Baseline 广泛可用 *

此特性已经十分成熟,可在许多设备和浏览器版本上使用。自 2020 年 7 月以来,它已在各大浏览器中可用。

* 此特性的某些部分可能存在不同级别的支持。

ResizeObserverEntry 接口代表传递给 ResizeObserver() 构造函数的回调函数的对象,它允许您访问被观察的 ElementSVGElement 的新尺寸。

实例属性

ResizeObserverEntry.borderBoxSize 只读

当回调运行时,包含被观察元素的新的边框盒尺寸的对象数组。

ResizeObserverEntry.contentBoxSize 只读

当回调运行时,包含被观察元素的新的内容盒尺寸的对象数组。

ResizeObserverEntry.devicePixelContentBoxSize 只读

当回调运行时,包含被观察元素以 设备像素 为单位的新的内容盒尺寸的对象数组。

ResizeObserverEntry.contentRect 只读

一个 DOMRectReadOnly 对象,包含当回调运行时被观察元素的新尺寸。请注意,这是为了向后兼容而保留在规范中的一个遗留属性。

ResizeObserverEntry.target 只读

对被观察的 ElementSVGElement 的引用。

注意: 内容盒是放置内容的盒子,即边框盒减去内边距和边框宽度。边框盒包含内容、内边距和边框。有关更多解释,请参阅 盒模型

实例方法

无。

示例

下面的代码片段摘自 resize-observer-text.html查看源代码)示例。

请注意,该代码涵盖了三种不同的兼容性情况:

  • 一些旧浏览器可能支持 contentRect 但不支持 contentBoxSize
  • Firefox 的旧版本支持 contentBoxSize,但错误地将其实现为一个对象而不是数组。
  • 现代浏览器支持 contentBoxSize 作为对象数组,以便它们能够报告碎片化元素的盒尺寸(例如,在多列场景中)。
js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      // The standard makes contentBoxSize an 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 {
        // … but old versions of Firefox treat it as a single item
        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);

规范

规范
Resize Observer(调整大小观察器)
# resize-observer-entry-interface

浏览器兼容性