场景:本人在做项目过程中想让滚动条滚动速度看起来自然点、想实现某个特定的时间内从慢到加速滚动的效果,偶然间看到 easeInOutCubi()方法、正是我要的效果。
easeInOutCubic(t, b, c, d)
四个参数:
t: 动画开始的指定时间。例如,t的值是0、表示动画刚刚开始。
b: 起始位置。如果b的值是10、表示从10这个位置开始移动。
c: 对象的指定值更改。例如如果c的值为30,则意味对象向上移动30。
d: 整个过程持续的时间。例如,d为500,则表示对象 500ms之内执行完成10到30。
function easeInOutCubic(t, b, c, d) {
var cc = c - b;
t /= d / 2;
if (t < 1) {
return (cc / 2) * t * t * t + b;
}
return (cc / 2) * ((t -= 2) * t * t + 2) + b;
}
// 实际项目里用的代码
const startTime = Date.now();
const duration = 500;
const frameFunc = () => {
const timestamp = Date.now();
const time = timestamp - startTime;
const nextScrollTop = easeInOutCubic(
time > duration ? duration : time,
treeListNode.scrollTop,
0,
duration,
);
treeListNode.scrollTop = nextScrollTop;
if (time < duration) {
setTimeout(() => {
frameFunc();
}, 15);
}
};
setTimeout(() => {
frameFunc();
}, 15);
}