How to use ResizeObserver

How to detect element size change?

No element will change for no reason. It may be that the size of the window changes. We can listen to the resize event of the window; but many cases are caused by changes (addition, deletion) of page elements, and it is more troublesome to deal with this situation. , most cases are also handled through custom events.

ResizeObserver provides a more direct method to directly monitor the size changes of elements.

How to use:

// 定义ResizeObserver对象,并设置监听方法
const myObserver = new ResizeObserver(entries => {
  // handleResize(entries)
})

const contentEle = document.querySelector('.content')
const staticEle = document.querySelector('p')

// 添加要监听的元素
myObserver.observe(staticEle)
myObserver.observe(contentEle)

The listener method parameter is an array, and each array object is an element whose size changes:

As can be seen from the above figure, each object has targetand contentRectattributes, and contentRectthe attributes include widthheight, xytoprightbottomleftThis is getBoundingClientRectvery similar to .

Since it is a relatively new method, the compatibility is poor:

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/130810002