ResizeObserverEntry:contentRect 属性
ResizeObserverEntry 接口的 contentRect 只读属性返回一个 DOMRectReadOnly 对象,其中包含在回调运行时观察到的元素的新大小。请注意,此属性比 ResizeObserverEntry.borderBoxSize 或 ResizeObserverEntry.contentBoxSize 得到更好的支持,但它是 Resize Observer API 早期实现的遗留物,仍出于 Web 兼容性原因包含在规范中,并可能在未来版本中被弃用。
值
一个 DOMRectReadOnly 对象,其中包含由 target 属性指示的元素的新大小。
如果 target 是 HTML Element,则返回的 contentRect 是元素的内容框(content box)。如果 target 是 SVGElement,则返回的 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 |
浏览器兼容性
加载中…