ResizeObserverEntry:contentRect 属性

Baseline 已广泛支持

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

ResizeObserverEntry 接口的 contentRect 只读属性返回一个 DOMRectReadOnly 对象,其中包含在回调运行时观察到的元素的新大小。请注意,此属性比 ResizeObserverEntry.borderBoxSizeResizeObserverEntry.contentBoxSize 得到更好的支持,但它是 Resize Observer API 早期实现的遗留物,仍出于 Web 兼容性原因包含在规范中,并可能在未来版本中被弃用。

一个 DOMRectReadOnly 对象,其中包含由 target 属性指示的元素的新大小。

如果 target 是 HTML Element,则返回的 contentRect 是元素的内容框(content box)。如果 targetSVGElement,则返回的 contentRect 是 SVG 的边界框(bounding box)。

示例

以下代码片段取自 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);

规范

规范
Resize Observer(调整大小观察器)
# dom-resizeobserverentry-contentrect

浏览器兼容性