缓动框架的封装
单个属性:
<button id="btn1">宽变400</button> <button id="btn2">运动到400</button> <div id="box"></div> <script> var box=document.getElementById("box"); var btn1=document.getElementById("btn1"); var btn2=document.getElementById("btn2"); btn1.onclick=function(){ animate(box,"width",400); } btn2.onclick=function(){ animate(box,"left",400); } function animate(ele,attr,target){ clearInterval(ele.timer); ele.timer=setInterval(function(){ var leader=parseInt(getStyle(ele,attr)) || 0; var step=(target-leader)/10; step=step>0?Math.ceil(step):Math.floor(step); ele.style[attr]=leader+step+"px"; if(Math.abs(target-leader)<=Math.abs(step)){ ele.style[attr] = target + "px"; clearInterval(ele.timer); } },30) } function getStyle(ele,attr){ if(ele.currentStyle){ return ele.currentStyle[attr]; }else{ return getComputedStyle(ele,false)[attr]; } } </script><style>
*{
margin: 0;
padding: 0;
}
#box{
width:100px;
height:100px;
background: pink;
position: absolute;
}
</style>
多个属性:
<style>
div {
position: absolute;
top: 40px;
left: 10px;
width: 100px;
opacity: 0.6;
height: 100px;
background-color: pink;
}
</style>
<button>运动到400然后回来</button> <div></div> <script> var btnArr = document.getElementsByTagName("button"); var div = document.getElementsByTagName("div")[0]; btnArr[0].onclick = function () { var json1 = {"left":300,"top":200,"width":300,"height":200,"opacity": 30,"zIndex": 1}; animate(div,json1); } function animate(ele,json,fn){ clearInterval(ele.timer); ele.timer = setInterval(function () { var bool = true; for(var k in json){ var leader; if(k === "opacity"){ leader = getStyle(ele,k)*100 || 1; }else{ leader = parseInt(getStyle(ele,k)) || 0; } var step = (json[k] - leader)/10; step = step>0?Math.ceil(step):Math.floor(step); leader = leader + step; if(k === "opacity"){ ele.style[k] = leader/100; ele.style.filter = "alpha(opacity="+leader+")"; }else if(k === "zIndex"){ ele.style.zIndex = json[k]; }else{ ele.style[k] = leader + "px"; } if(json[k] !== leader){ bool = false; } } if(bool){ clearInterval(ele.timer); if(fn){ fn(); } } },25); } function getStyle(ele,attr){ if(window.getComputedStyle){ return window.getComputedStyle(ele,null)[attr]; } return ele.currentStyle[attr]; } </script>