手写滚动条滚动动画
2021-03-11 本文已影响0人
不会写代码的机器人
/**
* 滚动动画
* @param {HTMLElenent} divDode -滚动条dom
* @param {number} position - 距离
* @param {'x'|'y'} direction - 滚动方向
* @param {number} time - 动画时间
*/
scrollAnimation(divDode, position, direction, time, fps) {
clearInterval(this.scrollManTimer);
divDode = divDode || window;
fps = fps || 16;
time = time || 300;
direction = direction || 'y';
let attr = direction === 'x' ? 'pageXOffset' : 'pageYOffset';
let attr2 = direction === 'x' ? 'scrollLeft' : 'scrollTop';
let scrollLength = divDode[attr] || divDode[attr2];
let count = 0;
let totalCount = Math.floor(time / fps);
let slice = (position - scrollLength) / totalCount;
this.scrollManTimer = setInterval(() => {
this.scroll(divDode, direction, slice);
count++;
if (count === totalCount) {
clearInterval(this.scrollManTimer);
let length = position - divDode[attr];
if (length === 0) return;
setTimeout(() => {
this.scroll(divDode, direction, length);
}, fps);
}
}, fps);
},
scroll(divDode, direction, number) {
divDode = divDode || window;
let x = direction === 'x' ? number : 0;
let y = direction === 'y' ? number : 0;
divDode.scrollBy(x, y);
},