<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS實現透明度漸變動畫</title> <style type="text/css"> *{margin:0;padding:0;} #box{width:200px;height:200px;background-color:red;filter:alpha(opacity=30);opacity:0.3;} </style> <script type="text/javascript"> window.onload = function(){ var box = document.getElementById('box'); box.onmouseover = function(){ changeopa(100); } box.onmouseout = function(){ changeopa(30); } } var timer; var opa=30; function changeopa(aim){ var box = document.getElementById('box'); clearInterval(timer); timer=setInterval(function(){ if(opa==aim){ clearInterval(timer); }else{ opa+=(aim-65)/3.5; box.style.opacity=opa/100; box.style.filter='alpha(opacity='+opa+')'; console.log(opa); } },30) } </script> </head> <body> <div id="box"></div> </body> </html>
遇到的問題及注意事項:
1、浮點運算進行多次后會出現誤差,盡量使用整數運算。