<!DOCTYPE HTML> <html lang="en/zh"> <head> <meta charset="UTF-8"> <title>JS_透明度动画</title> <style type="text/css"> *{ padding: 0px; margin: 0px; } #div1{ width: 200px; height: 200px; background: red; filter:alpha(opacity:30); /*ie低版本不支持opacity的 只支持filter */ opacity: 0.3; /*firefox,chrome*/ } </style> <script type="text/javascript"> window.onload=function(){ var oDiv=document.getElementById("div1"); oDiv.onmouseover=function(){ changeOpcity(100); } oDiv.onmouseout=function(){ changeOpcity(30); } } var timer=null; var alpha =30; function changeOpcity(target){ var oDiv=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ var speed = 0; if(alpha>target){ speed=-10; }else{ speed=10; } if(alpha==target){ clearInterval(timer); }else{ alpha+=speed; oDiv.style.filter='alpha(opacity:'+alpha+')';/*IE*/ oDiv.style.opacity=alpha/100; } },30); } </script> </head> <body> <div id="div1"> </div> </body> </html>
为什么不是一个值? 当然在变化,每一次间歇调用都在第二个if语句里对它进行了操作 并且让div的不透明度进行了变化。直到达到目标值才停止