vue监听dom元素的resize事件
# 一、监听 dom resize 事件
import ResizeObserver from 'resize-observer-polyfill'
const isServer = typeof window === 'undefined'
const resizeHandler = function(entries) {
for (let entry of entries) {
const listeners = entry.target.__resizeListeners__ || []
// entry.target监听的DOM对象,__resizeListeners__内容就遍历存储的监听回调
if (listeners.length) {
listeners.forEach((fn) => {
fn()
})
}
}
}
export const addResizeListener = function(element, fn) {
if (isServer) return
if (!element.__resizeListeners__) {
element.__resizeListeners__ = []
element.__ro__ = new ResizeObserver(resizeHandler)
element.__ro__.observe(element)
}
element.__resizeListeners__.push(fn)
}
export const removeResizeListener = function(element, fn) {
if (!element || !element.__resizeListeners__) return
element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1)
if (!element.__resizeListeners__.length) {
element.__ro__.disconnect()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
上次更新: 2023/04/05, 09:41:10