Youruncle
2016-08-17 11:23:06
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> div { width: 200px; height: 200px; background: red; filter: alpha(opacity: 30); opacity: 0.3; } </style> <script type="text/javascript"> window.onload=function(){ var odiv=document.getElementById("div1"); odiv.onmouseover=function(){ startMove(this,{width:400})? ? ? ? ? ? ? ? ? } odiv.onmouseout=function(){ startMove(this,{width:200})? ? ? ? ? ? ? ? ? } } function getStyle(obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; } else{ return getComputedStyle(obj,false)[name]; } } function startMove(obj,json,fnend){ clearInterval(obj.timer); obj.timer=setInterval(function(){ var Bstop=true; for (var attr in json) { if(attr=="opacity"){ cur=Math.round(parseFloat(getStyle(obj,attr))*100) } else{ cur=parseInt(getStyle(obj,attr)) } } var speed=(json[attr]-cur)/6; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(cur!=json[attr]) Bstop=false; if(attr=="opacity"){ obj.style.filter="alpha(opacity"+(speed+cur)+")"; obj.style.opacity=(speed+cur)/100 } else{ obj.style[attr]=speed+cur+"px" } if(Bstop){ clearInterval(obj.timer) if(fnend)fnend(); } }) } </script> </head> <body> <div id="div1"> </div> </body></html>
1 回答

stone310
TA貢獻361條經(jīng)驗 獲得超191個贊
首先明白Bstop的作用,是為了檢測最后所有屬性的值是否達到目標值(即動畫是否全部完成),是怎么檢測的呢,分三步
第一步,startMove這個函數(shù)是通過計時器不斷調(diào)用來完成動畫效果,那么它每次調(diào)用的時候Bstop都賦值為true(var Bstop=true)
第二步,if(cur!=json[attr])Bstop=false;是用來判斷當前元素的屬性值是否不等于你設定的目標值(即動畫是否還有沒完成的),如果不等于,那么Bstop就是false,這里if后面沒有{},說明如果條件成立,只執(zhí)行第一條語句,即Bstop=false;
第三步,最后那里有個if(Bstop){},相當于if(Bstop==true)就停止計時器,
現(xiàn)在可以發(fā)現(xiàn),如果第二步有動畫沒完成,那么Bstop是false,則第三步不成立,計時器不會停止,然后計時器繼續(xù)調(diào)用第一步,Bstop又變成true(第一步),然后繼續(xù)第二步,第三步,直到所有動畫完成,到了第三步Bstop還是true,那么就執(zhí)行第三步的停止計時器
添加回答
舉報
0/150
提交
取消