DOM & BOM – ResizeObserver
介绍
想监听一个 element 的 size changes 就可以使用 ResizeObserver 了.
在看这一篇之前, 建议先看看 , 它们的模式很像, 一起了解会比较容易.
效果
参考:
MDN – ResizeObserver
Youtube – Learn Resize Observer In 5 Minutes
场景
<body> <button class="button">resizebutton> <div class="box">resize mediv> body>
CSS Style
.box { margin-top: 3rem; width: 100px; height: 100px; background-color: pink; border: 2px solid red; padding: 1rem; }
new ResizeObserver()
const rs = new ResizeObserver((entries) => { console.log("entry", entries[0]); }); rs.observe(document.querySelector(".box")); document.querySelector(".button").addEventListener("click", () => { document.querySelector(".box").style.width = "400px"; });
调用, observe, unobserve 方式和 IntersectionObserver 是一样的.
new 实例 > observe > 当观察的元素 resize 就会触发回调. 不想观察了就 unobserve 或者直接 disconnect 整个 observer.
Callback Info
绿点是常用到的, 其它的就不介绍了
borderBoxSize, 它是 array 哦, 但我不知道什么时候会超过 1 个啦.
blockSize 就是 height, inlineSize 就是 width. 这个是 的写法.
ContentBoxSize, 顾名思义它就是依据 box-sizing: content-box 的计算方式 (width 不包含 padding 和 border).
contentRect: 它的 width 和 height 是扣除了 padding, border 的, 至于 rect, 它并不是 boundingClientRect 哦, 具体是什么坐标我也没去研究, 以后有需求在来补上呗.