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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值