<!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> <link rel="stylesheet" href="reset.css"> <style type="text/css"> .odiv{width:200px; height:200px; background:#f00; position:relative; left:0px; top:100px;opacity:0.3; filter:alpha(opacity:30); float:left; margin:10px;} </style></head><body><div id="odiv" class="odiv"></div></body></html><script language="javascript"> window.onload = function(){ var odiv = document.getElementsByTagName('div'); for(var i=0;i<odiv.length;i++) { odiv[i].onmouseover = function(){ startOP(this,100); } odiv[i].onmouseout = function(){ startOP(this,30); } odiv[i].timer = null;//事先定義 odiv[i].alpha = null;//事先定義 //這裏發現一個問題,對象的動畫屬性能夠不定義,可是透明度屬性必須定義,不然報錯 } } function startOP(obj,utarget){ clearInterval(obj.timer);//先關閉定時器 obj.timer = setInterval(function(){ var speed = 0; if(obj.alpha>utarget){ speed = -10; } else{ speed = 10; } obj.alpha = obj.alpha+speed; if(obj.alpha == utarget){ clearInterval(obj.timer); } obj.style.filter = 'alpha(opacity:'+obj.alpha+')';//基於IE的 obj.style.opacity = parseInt(obj.alpha)/100; },300); }</script>