<style> *{ margin: 0; padding: 0; } #box{ width: 200px; height: 200px; background-color: darkgoldenrod; position: absolute; top: 100px; left: 10px; }
</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,{left:200,top:400,width:400,height:400,opacity:30,zIndex:3},function () {alert(11)}); }; btn400.onclick = function () { animate(box,{left:400,top:800,width:200,height:200},function () {alert(11)}); }; //缓动效果函数 function animate(obj,json,fn) { clearInterval(obj.timer); obj.timer = setInterval(function () { var flag = true; //用来判断什么时候停止定时器 //遍历json for(var attr in json){ //获取当前属性的值,parseInt取数值,否则为字符串 var currentstyle = 0; if(attr == "opacity") { currentstyle = Math.round(parseInt(getStyle(obj,attr)*100)) || 0; //div中没有设置opacity时ie678会默认opacity为undefind } else { currentstyle = parseInt(getStyle(obj,attr)); } //计算步长 var step = (json[attr]-currentstyle)/10; step = step>0? Math.ceil(step): Math.floor(step); //向上或者向下取整 if(attr == "opacity") //如果json中有透明度 { if("opacity" in obj.style) //判断浏览器支持不支持opacity { obj.style.opacity = (currentstyle+step)/100; } else { obj.style.filter = "alpha(opacity = "+(currentstyle+step*10)+")"; //ie678 } } else if(attr == "zIndex") { obj.style.zIndex = json[attr]; } else { obj.style[attr] = currentstyle + step +"px"; } if(currentstyle != json[attr]) //判断有没有到达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]; } } /* //遍历json属性 var json = {width:100,height:100,left:10}; for(var k in json){ console.log(k); //获得的是属性 console.log(json[k]); //json[k]获得的是属性的值 }*/ </script>