<!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,opacity:40,zIndex:3},function(){alert("我是回调函数")});
}
btn400.onclick = function () {
animate(box,{left:100,opacity:10,zIndex:10})
}
function animate(obj,json,fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var flag = true;
for(var attr in json){
var current = 0;
if(attr == "opacity"){
current =parseInt(getStyle(obj,attr)*100);
}else{
current =parseInt(getStyle(obj,attr));
}
var step = (json[attr] - current) /10;
step = step>0 ? Math.ceil(step) : Math.floor(step);
if(attr == "opacity"){
if("opacity" in obj.style){
obj.style.opacity = (current+step)/100;
}else{
obj.style.filter = "alpha(opacity = "+(current+step)+")";
}
}else if(attr == "zIndex"){
obj.style.zIndex = json[attr];
}else{
obj.style[attr] = current + step + "px";
}
if(current != json[attr]){
flag = false;
}
}
if(flag){
clearInterval(obj.timer);
if(fn){fn();}
}
},30);
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,null)[attr];
}
}
</script>