9.使用原生js实现类似于jquery的动画
生活随笔
收集整理的這篇文章主要介紹了
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為濾鏡效果,也可以設置元素的透明度。
?
轉載于:https://www.cnblogs.com/binhuguang/p/4538122.html
總結
以上是生活随笔為你收集整理的9.使用原生js实现类似于jquery的动画的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oc调用rest api
- 下一篇: Java编程思想之-匿名内部类