通過alpha變數實現圖片透明度漸變(仍然用到JS緩衝運動框架)
阿新 • • 發佈:2019-02-13
程式思路:
實際上是一種運動。跟運動一樣的是,由一個透明度,運動到另一個透明度。
步驟:
1:寫一個Div為其賦值為半透明,相容FF和IE的相容,這樣寫css:
opacity:0.3;filter:alpha(opacity=30);
2:寫一個onload,獲取元素,併為元素新增onmouseover和onmouseout事件。
3:用勻速運動框架,或者緩衝運動框架,寫運動函式startMove(target)。當然緩衝運動更加自然一點。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文件</title> <style> #test{width:300px; height:300px; background:red; opacity:0.3; filter:alpha(opacity=30)} </style> <script> var timer=null; var speed=null; var alpha=30; window.onload=function(){ var oDiv=document.getElementById("test"); oDiv.onmouseover=function(){ startMove(100); } oDiv.onmouseout=function(){ startMove(30); } } function startMove(target){ var oDiv=document.getElementById("test"); clearInterval(timer); speed=target-alpha>0?Math.ceil((target-alpha)/10):Math.floor((target-alpha)/10); timer=setInterval(function(){ if(alpha==target){//停止條件 clearInterval(timer); } else{ alpha+=speed;//運動細節 oDiv.style.opacity=alpha/100; oDiv.style.filter="alpha(opacity:"+alpha+")";//由於不能直接獲得alpha只能用變數賦值了。 } },30); } </script> </head> <body> <div id="test"></div> </body> </html>