javascript 匀速运动完成淡入淡出

道理

  • 在做div或许图片淡入淡出的时刻,我们重要用到了透明度款式filter: alpha(opacity:30)兼容ie,opacity:0.3兼容火狐chrome。
  • 活动淡入淡出时用到了定时器setInterval;clearInterval;
  • js操纵淡入淡出时用下面情势修正透明度oDiv.style.filter=”alpha(opacity:”+alpha+”)”;oDiv.style.opacity=alpha/100;

注重:透明度没法直接在js中做推断,我们采纳alpha参数做比较,末了应用到对象上。

完成div淡入淡出

<!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>
    原文作者:666888
    原文地址: https://segmentfault.com/a/1190000016195736
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞