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