仿JQuery的show与hide动画函数
时间:2010-09-17 来源:Floyd
首先介绍两个工具函数:
1 //根据ID返回dom元素2 var $ = function(id){return document.getElementById(id);}
3 //返回dom元素的当前某css值
4 var getCss = function(obj,name){
5 //ie
6 if(obj.currentStyle) {
7 return obj.currentStyle[name];
8 }
9 //ff
10 else {
11 var style = document.defaultView.getComputedStyle(obj,null);
12 return style[name];
13 }
14 }
Hide函数:
1 var hide = function(obj,speed,fn){
23 obj = $(obj);
4
5 if (!speed) {
6 obj.style.display = 'none';
7 return;
8 }
9 else{
10 speed = speed==='fast'?30:speed==='normal'?50:70;
11 obj.style.overflow = 'hidden';
12 }
13 //获取dom的宽与高
14 var oWidth = getCss(obj,'width'), oHeight = getCss(obj,'height');
15 //每次dom的递减数(等比例)
16 var wcut = 20*(+oWidth.replace('px','') / +oHeight.replace('px','')),hcut = 20;
17 //处理动画函数
18 var process = function(width,height){
19 width = +width-wcut>0?+width-wcut:0;
20 height = +height-hcut>0?+width-hcut:0;
21 //判断是否减完了
22 if(width !== 0 || height !== 0) {
23 obj.style.width = width+'px';
24 obj.style.height = height+'px';
25
26 setTimeout(function(){process(width,height);},speed);
27 }
28 else {
29 //减完后,设置属性为隐藏以及原本dom的宽与高
30 obj.style.display = 'none';
31 obj.style.width = oWidth;
32 obj.style.height = oHeight;
33 if(fn)fn.call(obj);
34 }
35 }
36 process(oWidth.replace('px',''),oHeight.replace('px',''));
37 }
Show函数与Hide函数类似,只是思路相反而已
2
3 obj = $(obj);
4
5 if (!speed) {
6 obj.style.display = 'block';
7 return;
8 }
9 else{
10 speed = speed==='fast'?30:speed==='normal'?50:70;
11 obj.style.overflow = 'hidden';
12 }
13
14 var oWidth = getCss(obj,'width').replace('px',''), oHeight = getCss(obj,'height').replace('px','');
15 var wadd = 20*(+oWidth / +oHeight),hadd = 20;
16
17 obj.style.width = 0+'px';
18 obj.style.height = 0+'px';
19 obj.style.display = 'block';
20
21 var process = function(width,height){
22 width = +oWidth-width<wadd?+oWidth:wadd+width;
23 height = +oHeight-height<hadd?oHeight:hadd+height;
24
25 if(width !== +oWidth || height !== +oHeight) {
26 obj.style.width = width+'px';
27 obj.style.height = height+'px';
28
29 setTimeout(function(){process(width,height);},speed);
30 }
31 else {
32 obj.style.width = oWidth+'px';
33 obj.style.height = oHeight+'px';
34 if(fn)fn.call(obj);
35 }
36 }
37 process(0,0);
38 }
调用方式如:
1 hide('a','normal',function(){
2 show('a','normal');
3 });
呃。。。感觉写得好冗余,但不知要如何再优化,希望有高手能写个精简些的。。。
相关阅读 更多 +