本文分享一個透明度漸變效果的實作:元素初始透明度為 30,滑鼠移上時透明度慢慢增加到 100,移出時再慢慢減少回 30。
要點一:由於無法直接讀寫透明度值,可把透明度存到一個變數裡,讓變數變化後再賦值給元素的透明屬性。
var alpha=30;
要點二:比較目標值與當前透明值,判斷該用正向還是負向速度。
if(target > alpha){ speed = 2; }else{ speed = -2; }
要點三:透明值達到目標就關閉計時器,否則繼續變化,最後把值賦給元素。由於透明度有相容問題,需同時寫上 filter 與 opacity 兩種寫法。
if(alpha == target){ clearInterval(timer); } else{ alpha = alpha + speed; run.style.filter = 'alpha(opacity='+alpha+')'; run.style.opacity = alpha/100; document.title = alpha; }
完整程式碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>無標題文檔</title> <style> body{margin:0; padding:0;} #run{width:100px; height:100px; background:#06c; position:absolute; border:1px solid #000; opacity:0.3; filter:alpha(opacity=30);} </style> <script> window.onload = function(){ var run = document.getElementById("run"); var btn = document.getElementById("btn"); var speed = 1; var timer = null; var alpha=30; run.onmouseover = function(){ startrun(100); } run.onmouseout = function(){ startrun(30); } function startrun(target){ clearInterval(timer); timer = setInterval(function(){ if(target > alpha){ speed = 2; }else{ speed = -2; } if(alpha == target){ clearInterval(timer); } else{ alpha = alpha + speed; run.style.filter = 'alpha(opacity='+alpha+')'; run.style.opacity = alpha/100; document.title = alpha; } },30) } } </script> </head> <body> <div id="run"></div> </body> </html>
希望本文所述對大家的 JavaScript 程式設計有所幫助。