開發過程中總會遇到dom節點尺寸變化,去做一些相應的邏輯,第一想到的應該是用$(window).resize()去做,但是這個是監聽瀏覽器窗口的所以這個時候要用 ResizeObserver
ResizeObserver可以幫助我們監聽一個DOM節點的變化
1.節點的顯示和隱藏
2.節點的size變化
兼容性
ResizeObserver API使用了觀察者模式,也就是我們常說的發布-訂閱模式
var resizeObserver = new ResizeObserver(function( entries ) { // entries 是一個數組 里面有5個屬性能用到的只有兩個contentRect, target // contentRect 是dom的幾何信息 // target 和點擊事件里面的target一樣的 dom對象 entries.forEach((item, index) =>{ console.log(item.contentRect) }) })
完成代碼
html
<div class="box"></div> <button class="plus-width">加寬</button> <button class="plus-height">加高</button>
css
.box{ width: 100px; height: 100px; background-color: red; }
js
// 加寬
$('.plus-width').on('click', function(){
var width = $('.box').width()
setAttr('width',width)
})
// 加高 $('.plus-height').on('click', function(){
var height = $('.box').height()
setAttr('height',height)
})
// 設置
function setAttr(attr, value) {
value+=10
$('.box').css({[attr]: value+'px'})
}
var resizeObserver = new ResizeObserver(function( entries ) { // console.log(entries) entries.forEach((item, index) =>{ console.log(item.contentRect) }) })
// 監聽dom resizeObserver.observe(document.querySelector('.box'))
window.setTimeout(() => { resizeObserver.disconnect() // 此時就不會再監聽document.QuerySelector('.box')節點了 }, 4000)