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 |
瀏覽器相容性
載入中…