_constant
描述
返回常用的兼容性浏览器的 api,兼容),MutationObserver、requestAnimationFrame、cancelAnimationFrame
1、对浏览器 MutationObserver 做兼容处理, 详情使用查看 👉 MutationObserver (opens new window)
2、对原生浏览器自带的 window.requestAnimationFrame 做兼容处理
3、对原生浏览器自带的 window.cancelAnimationFrame 做兼容处理
# 1.示例
import { _constant } from 'sf-utils2'
const { _requestAnimationFrame, _requestAnimationFrame } = _constant
// requestAnimationFrame 示例
_requestAnimationFrame(() => {
console.log('屏幕hz刷新了')
})
// cancelAnimationFrame 示例
const start = Date.now()
let myReq
function step(timestamp) {
var progress = timestamp - start
console.log('打印', progress / 10)
if (progress < 2000) {
myReq = _requestAnimationFrame(step)
}
}
myReq = _requestAnimationFrame(step)
_requestAnimationFrame(myReq)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|
# 3.源码
源码,点开查看 👈
/**
* 观察DOM树结构发生变化(兼容)
*/
export const _MutationObserver = isBrowser()
? window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
: undefined
/**
* 兼容补间动画
*/
export const _requestAnimationFrame = (function () {
if (isBrowser()) {
const support = {
animationFrame: (
window?.requestAnimationFrame ||
window?.mozRequestAnimationFrame ||
window?.webkitRequestAnimationFrame ||
window?.msRequestAnimationFrame ||
window?.oRequestAnimationFrame
).bind(window)
}
return (
support.animationFrame ||
function (callback) {
window?.setTimeout(callback, 1000 / 60)
}
)
}
return undefined
})()
/**
* 取消补间动画
*/
export const _cancelAnimationFrame = (function () {
if (isBrowser()) {
return (
window?.cancelAnimationFrame ||
window?.mozCancelAnimationFrame ||
window?.cancelRequestAnimationFrame ||
function (id) {
clearTimeout(id)
}
)
}
})()
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
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
上次更新: 2025/07/01, 14:52:29