全国统一服务热线:400-633-9193

JS实现的透明度渐变动画效果示例

    网络     2018-05-18    1243

本文实例讲述了JS实现的透明度渐变动画效果。分享给大家供大家参考,具体如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
    <title>www.jb51.net JS透明度变化效果</title>
    <style>
    body{
      margin: 0px;
      padding: 0px;
    }
    .redb{
      width:200px;
      height: 200px;
      background: red;
      filter:alpha(opacity=30);
      opacity: 0.3;
    }
    </style>
  </head>
  <body>
    <div class="redb" id="opbtn"></div>
    <script>
    window.onload = function(){
      var opDiv = document.getElementById("opbtn");
      opDiv.onmouseover = function(){
        startMove(100);
      }
      opDiv.onmouseout = function(){
        startMove(30);
      }
    }
    var timer = null;
    var alpha = 30;
    var speed = 0;
    function startMove(opTarget){
      clearInterval(timer);
      var opDiv = document.getElementById("opbtn");
      timer = setInterval(function(){
        if(alpha<opTarget){
          speed = 10;
        }
        else if(alpha>opTarget){
          speed = -10;
        }
        if(alpha==opTarget){
          clearInterval(timer);
        }
        else{
          alpha += speed;
          opDiv.style.opacity = alpha/100;
          opDiv.style.filter = 'alpha(opacity='+alpha+')';
        }
      },100);
    }
    </script>
  </body>
</html>

运行效果:

小结:

1、filter和opacity区别:w3c标准透明度就是opacity,filter只有IE才能用,其他浏览器都支持opacity
2、改变透明度时候,不能通过类似offsetLeft的方法获取透明度值,因此需要单独创建变量
3、不要忘记将定时器赋值给timer


  分享到:  
0.2784s