记得给要移动的div加上绝对定位。
function my$(id) {
return document.getElementById(id);
}
function animate(element,target) {
clearInterval(element.timer);
element.timer=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.timer);
}
//测试代码
console.log("目标位置:"+target+",当前位置:"+current+",每次移动步数:"+step);
},20);
}
my$("btn1").onclick=function () {
animate(my$("dv"),400);
};
my$("btn2").onclick=function () {
animate(my$("dv"),800);
}