<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script>
var box = document.getElementById("box");
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
btn200.onclick = function () {
animate(box,200);
}
btn400.onclick = function () {
animate(box,400);
}
function animate(obj,target){
clearInterval(obj.timer);
var speed = obj.offsetLeft < target ? 5 : -5;
obj.timer = setInterval(function(){
var result = target - obj.offsetLeft;
obj.style.left = obj.offsetLeft + speed + "px";
if(Math.abs(result) <= 5){
clearInterval(obj.timer);
obj.style.left = target + "px";
}
},30);
}
</script>