利用Js中的定時器實現圖片的淡入淡出
阿新 • • 發佈:2018-12-20
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #div1 { height: 200px; width: 200px; background: #222222; filter: alpha(opacity:30);/**/ opacity:0.3;/*不支援IE瀏覽器*/ } </style> </head> <body> <div id="div1"> </div> <script> var oDiv = document.getElementById('div1'); var timer = null; var alpha = 30;/*alpha應該設定為全域性變數*/ var speed = 0; oDiv.onmouseover = function () { startMove(100); }; oDiv.onmouseout = function () { startMove(30); }; function startMove(iTarget) { clearInterval(timer); timer = setInterval(function () { if (alpha < iTarget) { speed = 10; } else { speed = -10; } if (alpha == iTarget) { clearInterval(timer); } else { alpha = alpha + speed; oDiv.style.filter = 'alpha(opacity:' + alpha + ')'; oDiv.style.opacity = alpha / 100; } }, 200); } </script> </body> </html>