DIV CSS 佈局教程網

JavaScript 動畫踩坑總整理:單物體與多物體運動的常見錯誤
編輯:關於JavaScript     

用 setInterval 做動畫,是每個前端新手都會走過的一段路。而這段路上最常撞到的幾個坑,幾乎都跟「計時器變數放哪裡」有關。以下把單物體與多物體兩類問題分開整理,並附上完整可用的框架。

一、單物體運動

問題一:if 不是迴圈

錯誤寫法:

 function startMove(){ var timer=null; var div1=document.getElementById("div1"); if (div1.offsetLeft==300){ clearInterval(timer); }else{ timer=setInterval(function(){ div1.style.left=div1.offsetLeft+10+"px"; },30) } }

原本希望元素走到 300px 就停下。問題在於 if 只判斷一次,不會在每次移動後重新檢查,所以計時器永遠不會被清除。

正確寫法是把判斷搬進計時器內部:

 var timer=null; function startMove(){ var div1=document.getElementById("div1"); timer=setInterval(function(){ if (div1.offsetLeft==300){ clearInterval(timer); } div1.style.left=div1.offsetLeft+10+"px"; },30) }

問題二:timer 宣告在函式裡

錯誤寫法:

 function startMove(){ var speed=1; var timer=null; var oDiv1=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ if (oDiv1.offsetLeft>=300){ clearInterval(timer); }else{ oDiv1.style.left=oDiv1.offsetLeft+speed+"px"; } },30) }

明明已經加了 clearInterval,連點幾次還是會加速。原因是 timer 宣告在 startMove 內部,每次點擊都會產生新的閉包與新的局部 timer,彼此互不相干,clearInterval 清的是一個剛被初始化為 null 的變數,自然清不掉上一輪的計時器。

正確做法是把 timer 提到全域:

 var timer=null; function startMove(){ var speed=1; var oDiv1=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ if (oDiv1.offsetLeft>=300){ clearInterval(timer); }else{ oDiv1.style.left=oDiv1.offsetLeft+speed+"px"; } },30) }

應用:分享欄滑出滑入

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style type="text/css"> #div1{ width: 150px; height: 200px; background: burlywood; position: absolute; left: -150px; } span{ width: 20px; height: 60px; position: absolute; background: gold; right: -20px; top: 70px; } </style> <script> window.onload=function(){ var oDiv1=document.getElementById("div1"); oDiv1.onmouseover=function(){ move(0); }; oDiv1.onmouseout=function(){ move(-150); }; }; var timer=null; function move(target){ var oDiv1=document.getElementById("div1"); var speed=0; if (oDiv1.offsetLeft<target){ speed=10; }else{ speed=-10; } clearInterval(timer); timer=setInterval(function(){ if(oDiv1.offsetLeft==target){ clearInterval(timer); }else{ oDiv1.style.left=oDiv1.offsetLeft+speed+"px"; } },30); } </script> </head> <body> <div id="div1"> <span id="span1">分享到</span> </div> </body> </html>

應用:圖片淡入淡出

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> #div1{ width: 200px; height: 200px; background: red; position: absolute; filter: alpha(opacity:30); opacity: 0.3; } </style> <script> window.onload=function(){ var oDiv1=document.getElementById("div1"); oDiv1.onmouseover=function(){ move(100); }; oDiv1.onmouseout=function(){ move(30); }; }; var timer=null; var alpha=30; function move(target){ var oDiv1=document.getElementById("div1"); var speed=0; clearInterval(timer); if(alpha<target){ speed=10; }else{ speed=-10; } timer=setInterval(function(){ if (alpha==target){ clearInterval(timer); }else{ alpha+=speed; oDiv1.style.filter="alpha(opacity:"+alpha+")"; oDiv1.style.opacity=alpha/100; } },30); }; </script> </head> <body> <div id="div1"> </div> </body> </html> 

這裡有兩個重點:JavaScript 沒有像 offsetLeft 那樣的透明度屬性,因此要自己維護一個 alpha 變數;設定時還得兼顧瀏覽器差異,舊 IE 走 style.filter = "alpha(opacity:x)",Chrome 與 Firefox 走 style.opacity = alpha/100。

應用:捲動時元素跟著移動

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style type="text/css"> #div1{ width: 100px; height: 100px; background: yellowgreen; position: absolute; bottom: 0px; right: 0px; } </style> <script> window.onscroll=function(){ var oDiv=document.getElementById("div1"); var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; move(document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop); }; var timer=null; function move(target){ var oDiv=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ var speed=(target-oDiv.offsetTop)/10; speed=speed>0?Math.ceil(speed):Math.floor(speed); if (oDiv.offsetTop==target){ clearInterval(timer); }else{ oDiv.style.top=oDiv.offsetTop+speed+'px'; } },30) }; </script> </head> <body style="height:2000px;"> <div id="div1"></div> </body> </html>

這裡出現了一個更好的做法:speed = (target - cur) / 10,讓速度隨距離自動衰減,再用 Math.ceil/Math.floor 確保一定會抵達終點。這種緩動比固定速度自然得多,也避免了因小數取捨而永遠到不了目標值的問題。

二、多物體運動

問題一:共用一個計時器

三個並排的 div 各自做伸縮時,若只宣告一個全域 timer,那麼當 A 還沒縮完、B 就觸發伸展,A 的計時器會被 B 覆蓋取消,動畫於是卡在中途。

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div{ width: 100px; height: 50px; background: yellow; margin: 10px; } </style> <script> window.onload=function(){ var oDiv=document.getElementsByTagName('div'); for (var i=0;i<oDiv.length;i++){ oDiv[i].timer=null; oDiv[i].onmouseover=function(){ move(300,this); }; oDiv[i].onmouseout=function(){ move(100,this); }; } }; function move(iTarget,oDiv){ clearInterval(oDiv.timer); oDiv.timer=setInterval(function(){ var speed=(iTarget-oDiv.offsetWidth)/5; speed=speed>0?Math.ceil(speed):Math.floor(speed); if (iTarget==oDiv.offsetWidth){ clearInterval(oDiv.timer); }else{ oDiv.style.width=oDiv.offsetWidth+speed+"px"; } },30); } </script> </head> <body> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> </body> </html>

解法很乾脆:給每個元素掛一個自己的 timer 屬性。這也是所有多物體動畫框架的基本手法——狀態跟著物件走,而不是放在全域。

問題二:多元素的淡入淡出

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div{ width: 200px; height: 200px; margin: 10px; background: yellow; float: left; filter: alpha(opacity:30); opacity: 0.3; } </style> <script> window.onload=function(){ var oDiv=document.getElementsByTagName('div'); for(var i=0;i<oDiv.length;i++){ oDiv[i].timer=null; oDiv[i].alpha=30; oDiv[i].onmouseover=function(){ move(100,this); }; oDiv[i].onmouseout=function(){ move(30,this); }; } }; function move(iTarget,obj){ clearInterval(obj.timer); obj.timer=setInterval(function(){ var speed=(iTarget-obj.alpha)/30; speed=speed>0?Math.ceil(speed):Math.floor(speed); if (obj.alpha==iTarget){ clearInterval(obj.timer); }else{ obj.alpha+=speed; obj.style.filter="alpha(opacity:"+obj.alpha+")"; obj.style.opacity=obj.alpha/100; } },30); } </script> </head> <body> <div></div> <div></div> <div></div> <div></div> </body> </html>

同樣地,alpha 也掛在元素身上,每個方塊各走各的節奏。

問題三:offsetWidth 的陷阱

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div{ width: 100px; height: 100px; margin: 10px; background: yellow; float: left; border: 10px solid black; } </style> <script> window.onload=function(){ var oDiv1=document.getElementById('div1'); var oDiv2=document.getElementById('div2'); oDiv1.timer=null; oDiv2.timer=null; oDiv1.onmouseover=function(){ move(this,400,'height'); }; oDiv1.onmouseout=function(){ move(this,100,'height'); }; oDiv2.onmouseover=function(){ move(this,400,'width'); }; oDiv2.onmouseout=function(){ move(this,100,'width'); }; }; function getStyle(obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; }else{ return getComputedStyle(obj,false)[name]; } }; function move(obj,iTarget,name){ clearInterval(obj.timer); obj.timer=setInterval(function(){ var cur=parseInt(getStyle(obj,name)); var speed=(iTarget-cur)/30; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(cur==iTarget){ clearInterval(obj.timer); }else{ obj.style[name]=cur+speed+"px"; } },30); }; </script> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> </html>

offsetWidth 取得的不只是內容寬度,還包含左右 padding 與 border。若元素有 10px 邊框,offsetWidth 就比實際 width 多了 20px;此時寫成 obj.style.width = obj.offsetWidth - 1 + "px",本意是每次縮小 1px,結果反而讓元素越變越大。正確做法是用 getStyle 讀取 computed width。另外,getStyle 回傳的是字串,必須用 parseInt 轉成數字才能做運算。

三、整合成通用框架

把上述經驗收攏起來,就得到一個能處理透明度、任意 CSS 屬性、多元素並行的運動框架:

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> #div1{ width: 200px; height: 200px; margin: 20px; background: yellow; border: 5px solid black; filter: alpha(opacity:30); opacity: 0.3; } </style> <script> window.onload=function(){ var oDiv1=document.getElementById('div1'); oDiv1.timer=null; oDiv1.onmouseover=function(){ move(this,100,'opacity'); }; oDiv1.onmouseout=function(){ move(this,30,'opacity'); }; }; function getStyle(obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; }else{ return getComputedStyle(obj,false)[name]; } }; function move(obj,iTarget,name){ clearInterval(obj.timer); obj.timer=setInterval(function(){ var cur=0; if(name=='opacity'){ cur=Math.round(parseFloat(getStyle(obj,name))*100); }else{ cur=parseInt(getStyle(obj,name)); } var speed=(iTarget-cur)/30; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(cur==iTarget){ clearInterval(obj.timer); }else{ if(name=='opacity'){ obj.style.opacity=(cur+speed)/100; obj.style.filter='alpha(opacity:'+cur+speed+')'; }else{ obj.style[name]=cur+speed+"px"; } } },30); }; </script> </head> <body> <div id="div1"></div> </body> </html>

四、今天該怎麼寫

手寫 setInterval 動畫的時代大致結束了。上述框架值得理解,因為它清楚呈現了「狀態存哪、終點怎麼判、如何避免計時器互相覆蓋」這三個核心問題;但實際開發時,請直接用 CSS transition 或 Web Animations API,瀏覽器會把它交給合成器執行,比主執行緒計時器順暢得多:

 element.animate([ { opacity: 0.3 }, { opacity: 1 } ], { duration: 300, easing: 'ease-out', fill: 'forwards' }); 

若需要複雜時間軸或大量元素,再考慮 GSAP 等專業動畫庫。而 scroll 事件中那種 frequent 觸發的運算,記得搭配 requestAnimationFrame 節流,避免每個捲動事件都排一次重繪。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved