动画
定时器
-
setIntervel
// setIntervel 是多次执行的定时器,它会在销毁之前一直重复执行
// 创建定时器
let timer = setInterval(() => {
// 需要循环执行的代码
if(conditions){
// 在不需要的时候清除定时器
clearInterval(timer);
}
}, 2000); // 设置循环执行的间隔
-
setTimeout
// setTineout 是只执行一次的定时器
let timer = setTimeout(() => {
// 需要执行的代码
}, 3000);// 设置定时器的延迟时间
匀速动画
function linearAnimation(ele, step, obj, callback){
clearInterval(ele.timer);
ele.timer = setInterval(function () {
let flag = true;
for (let key in obj){
let attr = key, target = obj[key]
let begin = parseInt(getComputedStyle(ele)[attr]) || 0;
step = (begin - target) > 0 ? (- step) : step;
if (Math.abs(target - begin) >= Math.abs(step)){
flag = false;
begin += step;
}else{
begin = target;
}
ele.style[attr] = begin + "px";
}
if (flag){
clearInterval(ele.timer);
callback && callback();
}
}, 20);
}
缓动动画
function easeAnimation(ele, obj, callback){
clearInterval(ele.timer);
let flag = true;
ele.timer = setInterval(function () {
for (let key in obj) {
let attr = key, target = obj[key];
let begin = parseInt(getComputedStyle(ele)[attr]) || 0;
let step = (target - begin) * 0.1;
if (Math.abs(step) > 1) {
flag = false;
begin += step;
} else {
begin = target;
}
ele.style[attr] = begin + "px";
}
if (flag) {
clearInterval(ele.timer);
callback && callback();
}
}, 30);
}