//设置任意的一个元素,移动到指定的目标位置 function animate(element, target) { clearInterval(element.timeId); //定时器的id值存储到对象的一个属中 element.timeId = setInterval(function () { //获取元素的当前的位置,数字类型 var current = element.offsetLeft; //每次移动的距离 var step = 10; step = current < target ? step : -step; //当前移动到位置 current += step; if (Math.abs(current - target) > Math.abs(step)) { element.style.left = current + "px"; } else { //清理定时器 clearInterval(element.timeId); //直接到达目标 element.style.left = target + "px"; } }, 10); } }
转载于:https://my.oschina.net/u/3848851/blog/1812025