<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 200px;
height: 200px;
background-color: darkgoldenrod;
position: absolute;
top: 100px;
left: 0;
}
</style>
<body>
<button id="btn200">btn200</button>
<button id="btn400">btn400</button>
<div id="box"></div>
</body>
<script>
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var box = document.getElementById("box");
btn200.onclick = function () {
animate(box,200);
};
btn400.onclick = function () {
animate(box,400);
};
function animate(obj,target) {
clearInterval(obj.timer); //清除定时器
obj.timer = setInterval(function () {
var step = (target-obj.offsetLeft)/10;
step = step>0? Math.ceil(step): Math.floor(step);
obj.style.left = obj.offsetLeft + step +"px";
if (obj.offsetLeft == target){
clearInterval(obj.timer);
}
},30)
}
</script>