-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (59 loc) · 1.37 KB
/
index.js
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
/**
* add listener on change of element layout size.
*
* @author lakca<[email protected]>
* @param {HTMLElement} ele
* @param {object} [opts]
* @param {number} [opts.frame=30]
* @param {function} [opts.getSize=getSize] see default value below
* @param {function} [opts.equal=equal] see default value below
* @param {function} cb
* @returns {function} remove the listener.
*/
module.exports = function onresize(ele, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
opts = Object.assign({ frame: 30, getSize, equal }, opts)
let currentSize = opts.getSize(ele)
let handler = frame()
let count = 0
exec(currentSize)
return function cancel() {
window.cancelAnimationFrame(handler)
}
function frame() {
return window.requestAnimationFrame(function() {
handler = frame()
if (++count < opts.frame) {
return
} else {
count %= opts.frame
}
exec(opts.getSize(ele), currentSize)
})
}
function exec(size, lastSize) {
try {
if (!opts.equal(lastSize, size)) {
cb(size)
}
} finally {
lastSize = size
}
}
}
function getSize(ele) {
return {
width: ele.offsetWidth,
height: ele.offsetHeight
}
}
function equal(one, other) {
if (one && other) {
return one.width === other.width && one.height === other.height
} else {
return false
}
}