Simple easing animation function:
animate(obj, target, time, callback);
Note: The
obj
target object, need to add absolute positioning
target
: target position
time
: animation interval time
callback
: callback function
Code:
function animate(obj, target, time, callback) {
// 先清除以前的定时器,只保留当前的一个定时器执行
clearInterval(obj.timer);
obj.timer = setInterval(function() {
// 步长值写到定时器的里面,并设置为整数,缓动效果
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
// 回调函数写到定时器结束里面
callback && callback();
}
obj.style.left = obj.offsetLeft + step + 'px';
}, time);
}