动画setInterval

var timerId = null;
// 封装动画的函数
function animate(element, target) {

// 通过判断,保证页面上只有一个定时器在执行动画
if (timerId) {
clearInterval(timerId);
timerId = null;
}

timerId = setInterval(function () {
// 步进 每次移动的距离
var step = 10;
// 盒子当前的位置
var current = element.offsetLeft;

if (current >= target) {
// 让定时器停止
clearInterval(timerId);
// 让盒子到target的位置
element.style.left = target + 'px';
return;
}
// 移动盒子
current += step;
element.style.left = current + 'px';
}, 30);
}

原文地址:https://www.cnblogs.com/pxxdbk/p/12655039.html