JS实现透明度渐变动画

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS实现透明度渐变动画</title>
  <style type="text/css">
  *{margin:0;padding:0;}
  #box{width:200px;height:200px;background-color:red;filter:alpha(opacity=30);opacity:0.3;}
  </style>
  <script type="text/javascript">
    window.onload = function(){
      var box = document.getElementById('box');
      box.onmouseover = function(){
        changeopa(100);
      }
      box.onmouseout = function(){
        changeopa(30);
    }
  }

    var timer;
    var opa=30;
    
    function changeopa(aim){
      var box = document.getElementById('box');
      clearInterval(timer);
      timer=setInterval(function(){
        if(opa==aim){
          clearInterval(timer);
        }else{
          opa+=(aim-65)/3.5;
          box.style.opacity=opa/100;
          box.style.filter='alpha(opacity='+opa+')';
          console.log(opa);
        }
      },30)
    }

  </script>
</head>
<body>
  <div id="box"></div>
</body>
</html>

遇到的问题及注意事项:

1、浮点运算进行多次后会出现误差,尽量使用整数运算。

posted @ 2017-05-15 16:42  oliverlht  阅读(3843)  评论(1编辑  收藏  举报