注意obj.timer =setInterval()这个用法。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#run{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="run"></div>
</body>
</html>
<script>
function $(id){return document.getElementById(id)}
$("btn200").onclick = function () {
animate($("run"),200);
}
$("btn400").onclick = function () {
animate($("run"),400);
}
function animate(obj,target){
obj.timer = setInterval(function(){
if(obj.offsetLeft > target){
clearInterval(obj.timer);
}
obj.style.left = obj.offsetLeft + 10 + "px";
},30);
}
</script>