示例:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><style>.observedDiv {width: 40vw;height: 50vh;background-color: lightblue;}</style></head><body><div id="observedDiv" class="observedDiv">这个 div 的宽高会被监听。</div><script>const observedDiv = document.getElementById('observedDiv')const resizeObserver = new ResizeObserver(entries => {for (let entry of entries) {const { width, height } = entry.contentRectconsole.log(`新的宽度: ${width}px,新的高度: ${height}px`)}})// 开启监听resizeObserver.observe(observedDiv)setTimeout(() => {console.log('停止监听了')// 卸载监听-指定domresizeObserver.unobserve(observedDiv)// 卸载监听-所有// resizeObserver.disconnect();}, 5000)</script></body>
</html>