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、浮点运算进行多次后会出现误差,尽量使用整数运算。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM