9.使用原生js实现类似于jquery的动画

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="gb2312" />
 5 <title>无标题文档</title>
 6 <style>
 7 <!--
 8 body{margin:0; padding:0; font:12px/1.5 arial;}
 9 #box{width:100px; height:100px; position:absolute; background:#06c; left:0;filter:alpha(opacity=30); opacity:0.3;}
10 -->
11 </style>
12 <script>
13 function getstyle(obj,name){
14   if(obj.currentStyle){
15       return obj.currentStyle[name];
16     }else{
17       return getComputedStyle(obj,false)[name];
18     }
19 }
20 
21 window.onload = function(){
22   var box = document.getElementById("box");
23     box.onmouseover = function(){
24       startrun(box,"width",200,function(){
25           startrun(box,"height",200,function(){
26               startrun(box,"opacity","100");
27             });
28         });
29     };
30     box.onmouseout = function(){
31       startrun(box,"height",100,function(){
32           startrun(box,"width",100,function(){
33               startrun(box,"opacity","30");
34             });
35         });
36     };
37 };
38 
39 function startrun(obj,attr,target,fn){
40     clearInterval(obj.timer);
41     obj.timer = setInterval(function(){
42       var cur = 0;
43         if(attr == "opacity"){
44           cur = Math.round(parseFloat(getstyle(obj,attr))*100);
45         }else{
46           cur = parseInt(getstyle(obj,attr));
47         }
48       var speed = (target-cur)/8;
49         speed = speed>0?Math.ceil(speed):Math.floor(speed);
50         
51         if(cur == target){
52           clearInterval(obj.timer);
53             if(fn){
54               fn();
55             }
56         }else{
57           if(attr == "opacity"){
58                 obj.style.filter = "alpha(opacity="+(cur+speed)+")";
59               obj.style.opacity = (cur+speed)/100;
60             }else{
61             obj.style[attr] = cur + speed + "px";
62             }
63         }
64         
65     } ,30);
66 }
67 //-->
68 </script>
69 </head>
70 
71 <body>
72 <div id="box">
73 </div>
74 </body>
75 </html>

要点:

1.用js的style属性可以获得html标签的样式,但是不能获取非行间样式。那么怎么用js获取css的非行间样式呢?在IE下可以用currentStyle,而在火狐下面我们需要用到getComputedStyle。

2.opacity可以设置块的透明度,filter为滤镜效果,也可以设置元素的透明度。

 

posted @ 2015-05-29 11:43  小宾童鞋学吐槽  阅读(298)  评论(0)    收藏  举报