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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import XEUtils from 'xe-utils/methods/xe-utils'
import GlobalConfig from '../../conf'
import DomTools from '../../tools/src/dom'
/**
* 监听 resize 事件
* 如果项目中已使用了 resize-observer-polyfill,那么只需要将方法定义全局,该组件就会自动使用
*/
let resizeTimeout
const eventStore = []
const defaultInterval = 250
class ResizeObserverPolyfill {
constructor (callback) {
this.tarList = []
this.callback = callback
}
observe (target) {
if (target) {
if (this.tarList.indexOf(target) === -1) {
this.tarList.push({
target,
width: target.clientWidth,
heighe: target.clientHeight
})
}
if (!eventStore.length) {
eventListener()
}
if (!eventStore.some(item => item === this)) {
eventStore.push(this)
}
}
}
unobserve (target) {
XEUtils.remove(eventStore, item => item.tarList.indexOf(target) > -1)
}
disconnect () {
XEUtils.remove(eventStore, item => item === this)
}
}
const Resize = DomTools.browse.isDoc ? (window.ResizeObserver || ResizeObserverPolyfill) : ResizeObserverPolyfill
function eventListener () {
clearTimeout(resizeTimeout)
resizeTimeout = setTimeout(eventHandle, GlobalConfig.resizeInterval || defaultInterval)
}
function eventHandle () {
if (eventStore.length) {
eventStore.forEach(item => {
item.tarList.forEach(observer => {
const { target, width, heighe } = observer
const clientWidth = target.clientWidth
const clientHeight = target.clientHeight
const rWidth = clientWidth && width !== clientWidth
const rHeight = clientHeight && heighe !== clientHeight
if (rWidth || rHeight) {
observer.width = clientWidth
observer.heighe = clientHeight
requestAnimationFrame(item.callback)
}
})
})
eventListener()
}
}
export default Resize