js滚动动画

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
/**
* 滚动动画函数
* @param el 元素对象或者元素id
* @param targetPosition 滚动条目标位置
* @param duringTime 持续时间 默认300
* @param onComplete 滚动完成触发
*/
export function scrollAnimate({el, targetPosition, duringTime = 300, onComplete}) {
if (typeof el === 'string') {
el = document.getElementById(el);
}

if (!targetPosition) return;

const startTime = (new Date()).getTime();

function animate() {
const nowTime = (new Date()).getTime();
const elapsed = nowTime - startTime;
const fraction = elapsed / duringTime;
const position = targetPosition - el.scrollTop;
if (fraction < 1) {
el.scrollTop += fraction * position * Math.sin(Math.PI / 2);
setTimeout(animate, Math.min(25, duringTime - elapsed));
} else {
el.scrollTop = targetPosition;
if (onComplete) {
onComplete();
}
}
}

animate();
}