淡入淡出效果
淡入淡出效果
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <style> 7 #img1{opacity: 0.3; filter: alpha(opacity=30)} 8 </style> 9 <script> 10 window.onload = function(){ 11 var oImg = document.getElementById('img1'); 12 13 oImg.onmouseover = function(){ 14 startMove(100); 15 } 16 17 oImg.onmouseout = function(){ 18 startMove(30); 19 } 20 } 21 var alpha = 30; //透明度的当前值,中间变量 22 var timer = null; 23 function startMove(iTarget){ 24 var oImg = document.getElementById('img1'); 25 var speed = null; 26 clearInterval(timer); 27 timer = setInterval(function(){ 28 //判断速度的正负 29 if(alpha < iTarget){ 30 speed = 2; 31 }else{ 32 speed = -2; 33 } 34 //运动和停止分开 35 if(alpha == iTarget){ 36 clearInterval(timer); 37 }else{ 38 alpha += speed; 39 40 oImg.style.opacity = alpha / 100; 41 oImg.style.filter = "alpha(opacity=" + alpha + ")"; 42 43 } 44 45 //document.title = alpha; 46 }, 30); 47 } 48 49 /* 50 如果我们遇到这种透明度类型的兼容性写法,我们可以通过【中间变量】方式去辅助我们计算。 51 */ 52 53 </script> 54 </head> 55 <body> 56 <img id = 'img1' src="img/060222vdfceizbtiqtwddw.jpg" alt=""> 57 </body> 58 </html>
浏览器效果:
示例中用到的图片:
附加两种图片(与示例无关):