Home >Web Front-end >JS Tutorial >Javascript uniform motion to achieve fade-in and fade-out effect (code)
The content of this article is about the fade-in and fade-out effect of JavaScript uniform motion (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
When doing p or picture fade-in and fade-out, we mainly use the transparency style filter: alpha(opacity:30) is compatible with ie, opacity:0.3 is compatible Firefox chrome.
When the motion fades in and out, the timer setInterval;clearInterval;
When js operates to fade in and out, use the following form to modify the transparency op.style. filter="alpha(opacity:" alpha ")";op.style.opacity=alpha/100;
Note: transparency cannot be judged directly in js, we use the alpha parameter Do the comparison and finally apply it to the object.
<!DOCTYPE html> <html> <head> <title>div淡入淡出</title> <style> #div1{ width: 200px; height: 200px; background: red; /* ie */ filter: alpha(opacity:30); /* chrome firefox */ opacity:0.3; } </style> <script> window.onload=function(){ var oDiv=document.getElementById("div1"); oDiv.onmouseover=function(){ startMove(100); } oDiv.onmouseout=function(){ startMove(30); } } var timer=null; var alpha=30;//透明度默认30 function startMove(iTarget){ var oDiv=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ var speed=0; if(alpha<iTarget){ speed=5; }else{ speed=-5; } 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>
<!DOCTYPE html> <html> <head> <title>图片淡入淡出</title> <style> #img1{ /* ie */ filter: alpha(opacity:30); /* chrome firefox */ opacity: 0.3; border: 1px solid #000; } </style> <script> window.onload=function(){ var oImg=document.getElementById("img1"); oImg.onmouseover=function(){ startMove(100); } oImg.onmouseout=function(){ startMove(30); } } var timer=null; var alpha=30;//透明度默认30 function startMove(iTarget){ var oImg=document.getElementById("img1"); clearInterval(timer); timer=setInterval(function(){ var speed=0; if(alpha<iTarget){ speed=5; }else{ speed=-5; } if(alpha===iTarget){ clearInterval(timer); }else{ alpha+=speed; oImg.style.filter="alpha(opacity:"+alpha+")"; oImg.style.opacity=alpha/100; } },30); } </script> </head> <body> <img id="img1" src="img1.jpg" alt=""> </body> </html>
Related recommendations:
javascript uniform motion to achieve sidebar sharing effect ( Code)
js to realize uniform fade-in and fade-out of images
Use jQuery to realize advertising scrolling and fade-in and fade-out
The above is the detailed content of Javascript uniform motion to achieve fade-in and fade-out effect (code). For more information, please follow other related articles on the PHP Chinese website!