var flag = true; //用来判断是否停止定时器 一定要写在遍历外面
if(current != json[attr]){ //只要目标与json中任意一个值不等 就不能停止定时器 这个一定写在定时器里面
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
position: absolute;
top: 50px;
left: 5px;
background-color: pink;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script>
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var box = document.getElementById("box");
btn200.onclick = function () {
animate(box,{width:200,height:300,top:400});
}
btn400.onclick = function () {
animate(box,{left:100})
}
function animate(obj,json){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var flag = true; //用来判断是否停止定时器 一定要写在遍历外面
for(var attr in json){
var current =parseInt(getStyle(obj,attr)); //数值
var step = (json[attr] - current) /10;
step = step>0 ? Math.ceil(step) : Math.floor(step);
obj.style[attr] = current + step + "px";
if(current != json[attr]){ //只要目标与json中任意一个值不等 就不能停止定时器 这个一定写在定时器里面
flag = false;
}
}
if(flag){
clearInterval(obj.timer);
alert("ok");
}
},30);
}
function getStyle(obj,attr){ //获取属性值
if(obj.currentStyle){ //i3
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,null)[attr]; //w3c
}
}
</script>