变速动画函数封装

//匀速动画
function animate(element,target) {
//清理定时器
clearInterval(element.timeId);
element.timeId=setInterval(function () {
//获取元素当前位置
var current=element.offsetLeft;
//移动的步数
var step=(target-current)/10;
step=step>0?Math.ceil(step):Math.floor(step);
current+=step;
element.style.left=current+"px";
if(current==target){
//清理计时器
clearInterval(element.timeId);
}
//测试代码
console.log("目标位置:"+target+",当前位置:"+current+",每次移动的步数:"+step)
},20);
}

猜你喜欢

转载自www.cnblogs.com/lujieting/p/10055225.html