跟其他物体运动略有不同,物体透明度在IE9以下版本有不兼容的情况,因此要用filter:alpha(opacity:30);这样的写法兼容,我们需要声明一个变量alpha = 30;来保存一下当前的透明度,再通过改变变量的值来修改透明度。当然用JQ的fadeIn和fadeOut也可以实现同样的效果,而且更加简便。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>淡入淡出</title> <style> #div1{width: 200px; height: 200px; background: blue; position: absolute; top:50px; left: 0px; filter:alpha(opacity:30); opacity: 0.3;} </style> <script type="text/javascript"> window.onload = function(){ var oDiv = document.getElementById('div1'); oDiv.onmouseover = function(){ StartMove(100); } oDiv.onmouseout = function(){ StartMove(30); } }; var timer = null; var alpha = 30; function StartMove(iTarget){ var oDiv = document.getElementById('div1'); clearInterval(timer); timer = setInterval(function(){ var speed = 0; if(alpha>iTarget) { speed = -10; } else { speed = 10; } if(alpha == iTarget) { clearInterval(timer); } else { alpha += speed; oDiv.style.filter = 'alpha(opacity:'+alpha+')'; oDiv.style.opacity = alpha/100; } },30); } </script> </head> <body> <div id = "div1"></div> </body> </html>