<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>js监听dom大小改变的实现示例,支持vue</title>
<style>
#asaidom {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<p id="asaidomsize"></p>
<p id="asaidom"></p>
<button id="btn">改大小</button>
<script>
var asaiDomSize = document.getElementById("asaidomsize");
var asaiDom = document.getElementById("asaidom");
// 方案一:html上可以用,vue中无法使用
const moServer =
window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver;
const observer = new moServer((mutations) => {
console.log("666.909", mutations);
});
observer.observe(asaiDom, {
attributes: true,
attributeFilter: ["style"],
attributeOldValue: true,
});
// 方案二:html可用,vue可用(推荐)
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
// console.log(entry.target.style.width); // 仅适用于真的改变了style样式中的width
asaiDomSize.innerText = document.defaultView.getComputedStyle(
entry.target
).width;
console.log(
666.9098,
document.defaultView.getComputedStyle(entry.target).width
);
}
});
resizeObserver.observe(asaiDom);
document.getElementById("btn").onclick = function () {
asaiDom.style.width = parseInt(Math.random() * 100) + "px";
};
</script>
</body>
</html>
js监听dom大小改变的实现示例,支持vue
于 2023-08-25 08:41:27 首次发布