语法
js
observe(target)
observe(target, options)
参数
目标-
要观察的
Element或SVGElement的引用。 options可选-
一个选项对象,允许你设置观察选项。目前它只有一个可以设置的选项
box-
设置观察者将观察的盒模型变化。可能的值包括
content-box(默认值)-
内容区域的大小,如 CSS 中所定义。
border-box-
边框区域的大小,如 CSS 中所定义。
device-pixel-content-box-
内容区域的大小,如 CSS 中所定义,以设备像素为单位,在对元素或其祖先应用任何 CSS 变换之前。
返回值
无(undefined)。
异常
无。
示例
以下代码片段取自 resize-observer-text.html (查看源代码) 示例
js
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
if (entry.contentBoxSize) {
// Checking for chrome as using a non-standard array
if (entry.contentBoxSize[0]) {
h1Elem.style.fontSize = `${Math.max(
1.5,
entry.contentBoxSize[0].inlineSize / 200,
)}rem`;
pElem.style.fontSize = `${Math.max(
1,
entry.contentBoxSize[0].inlineSize / 600,
)}rem`;
} else {
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`;
}
}
console.log("Size changed");
});
resizeObserver.observe(divElem);
使用选项对象的 observe() 调用示例如下所示
js
resizeObserver.observe(divElem, { box: "border-box" });
规范
| 规范 |
|---|
| Resize Observer(调整大小观察器) # dom-resizeobserver-observe |
浏览器兼容性
加载中…