ResizeObserverEntry: contentBoxSize 属性

Baseline 已广泛支持

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

ResizeObserverEntry 接口的只读属性 contentBoxSize 在回调运行时,返回一个包含被观察元素新内容框尺寸的数组。

一个包含新内容框尺寸对象的数组。该数组是必需的,以支持具有多个片段的元素,这在多列场景中会出现。数组中的每个对象都包含两个属性:

blockSize

被观察元素的块级尺寸内容框的长度。对于具有水平 writing-mode 的框,这是垂直尺寸,即高度;如果 writing-mode 是垂直的,这是水平尺寸,即宽度。

inlineSize

被观察元素的内联尺寸内容框的长度。对于具有水平 writing-mode 的框,这是水平尺寸,即宽度;如果 writing-mode 是垂直的,这是垂直尺寸,即高度。

注意: 有关书写模式以及块维度和内联维度的更多解释,请阅读 处理不同的文本方向

示例

以下代码段摘自 resize-observer-border-radius.html查看源代码)示例。该示例包含一个绿色框,其大小根据视口大小的百分比来确定。当视口大小改变时,框的圆角会根据框的大小成比例变化。我们本可以使用百分比的 border-radius 来实现这一点,但这很快就会导致难看的椭圆形角;此解决方案可提供漂亮的方形角,可随框的大小缩放。

js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      // The standard makes contentBoxSize an array...
      if (entry.contentBoxSize[0]) {
        entry.target.style.borderRadius = `${Math.min(
          100,
          entry.contentBoxSize[0].inlineSize / 10 +
            entry.contentBoxSize[0].blockSize / 10,
        )}px`;
      } else {
        // … but old versions of Firefox treat it as a single item
        entry.target.style.borderRadius = `${Math.min(
          100,
          entry.contentBoxSize.inlineSize / 10 +
            entry.contentBoxSize.blockSize / 10,
        )}px`;
      }
    } else {
      entry.target.style.borderRadius = `${Math.min(
        100,
        entry.contentRect.width / 10 + entry.contentRect.height / 10,
      )}px`;
    }
  }
});

resizeObserver.observe(document.querySelector("div"));

规范

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

浏览器兼容性