自建设网站网络营销以什么为中心
一、与 MutationObserver Api的区别
- MutationObserver 主要用来监听 DOM 元素的属性和节点变化的,非 DOM 样式尺寸,可查看之前一篇 blog - DOM规范 - MutationObserver接口观察DOM元素的属性和节点变化
- ResizeObserver 主要用来监听 DOM 元素的 内容区域 的尺寸变化,可以监听到 Element 的内容区域或 SVGElement 的边界框改变
二、用法
1. 构造函数,创建并返回一个 ResizeObserver 对象
const resizeObserver = new ResizeObserver(entries => {console.log('监听到了尺寸变化了...', entries)
})resizeObserver.observe(document.getElementById('box'))
-
resizeObserver 是返回的一个操作对象,可调用其中的方法来监听、取消监听 DOM 元素等操作。
-
observe 方法用于开始观察指定的 Element 或 SVGElement 的尺寸变化。
-
entries 参数返回是一个数组,里面包含监听的每个 DOM 元素的相关信息,其中 contentRect 包含的是变化后的 内容区域 的尺寸信息。
2. unobserve 结束观察指定的 Element 或 SVGElement
resizeObserver.unobserve(document.getElementById('box'))
3. disconnect 取消和结束目标对象上所有对 Element或 SVGElement 观察
resizeObserver.disconnect()
三、完整栗子及注意点~
-
#box1 是 标准盒模型(w3c标准),width = 内容区(content),height 同理。
-
#box2 是边框盒模型(IE盒模型),width = 内容区(content)+ 内边距(padding) + 内边框(border),height 同理。
<!DOCTYPE html>
<html lang="zh_CN">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ResizeObserver 测试</title><style>body {margin: 0;}#box1 {width: 200px;height: 200px;margin: 10px;padding: 10px;background-color: rgb(195, 245, 175);}#box2 {width: 200px;height: 200px;margin: 10px;padding: 10px;box-sizing: border-box; /** 注意,此处盒模型与 #box1 不同 */background-color: rgb(175, 182, 245);}</style>
</head>
<body><button onclick="change1()">更改box1样式</button><button onclick="change2()">更改box2样式</button><button onclick="cancel1()">取消监听box1</button><button onclick="cancel2()">取消监听box2</button><button onclick="cancel()">取消所有元素</button><div id="box1">这是一个测试盒子111~~~</div><div id="box2">这是一个测试盒子222~~~</div><script>const box1 = document.getElementById('box1')const box2 = document.getElementById('box2')let b1width = 1let b2width = 1const resizeObserver = new ResizeObserver(entries => {console.log('监听到了尺寸变化了...', entries)})resizeObserver.observe(box1)resizeObserver.observe(box2)function change1 () {const rect = box1.getBoundingClientRect()// box1.style.width = rect.width + 10 + 'px'// 因 #box1 是标准盒,所以边框(border)尺寸变化不会引起内容区(content)尺寸变化,所以以下语句`不会`触发观察的回调函数事件box1.style.border = 1 + b1width + 'px solid red'b1width ++}function change2 () {const rect = box2.getBoundingClientRect()// box2.style.width = rect.width + 10 + 'px'// 因 #box2 是边框盒,所以边框(border)尺寸变化会引起内容区(content)尺寸变化,所以以下语句`会`触发观察的回调函数事件box2.style.border = 1 + b2width + 'px solid red'b2width ++}function cancel1 () {resizeObserver.unobserve(box1)}function cancel2 () {resizeObserver.unobserve(box2)}function cancel () {resizeObserver.disconnect()}</script>
</body>
</html>
打印信息
盒模型示意图