//Return dom element according to ID
var $ = function( id){return document.getElementById(id);}
//Return the current css value of the dom element
var getCss = function(obj,name){
//ie
if(obj .currentStyle) {
return obj.currentStyle[name];
}
//ff
else {
var style = document.defaultView.getComputedStyle(obj,null);
return style[name];
}
}
Hide function:
var hide = function(obj,speed,fn){
obj = $(obj);
if (!speed) {
obj.style.display = 'none';
return;
}
else{
speed = speed==='fast'?20:speed==='normal' ?30:50;
obj.style.overflow = 'hidden';
}
//Get the width and height of dom
var oWidth = getCss(obj,'width'), oHeight = getCss(obj,'height');
//The decrement number of dom each time (equal proportion)
var wcut = 10*( oWidth.replace('px','') / oHeight.replace(' px','')),hcut = 10;
//Process animation function
var process = function(width,height){
width = width-wcut>0? width-wcut:0;
height = height-hcut>0? width-hcut:0;
//Judge whether the reduction is complete
if(width !== 0 || height !== 0) {
obj. style.width = width 'px';
obj.style.height = height 'px';
setTimeout(function(){process(width,height);},speed);
}
else {
//After reduction, set the attributes to hidden and the width and height of the original dom
obj.style.display = 'none';
obj.style.width = oWidth;
obj.style.height = oHeight;
if(fn)fn.call(obj);
}
}
process(oWidth.replace('px',''), oHeight.replace('px',''));
}
Show function is similar to Hide function, but the idea is opposite
var show = function(obj,speed,fn){
obj = $( obj);
if (!speed) {
obj.style.display = 'block';
return;
}
else{
speed = speed== ='fast'?20:speed==='normal'?30:50;
obj.style.overflow = 'hidden';
}
var oWidth = getCss(obj,' width').replace('px',''), oHeight = getCss(obj,'height').replace('px','');
var wadd = 10*( oWidth / oHeight),hadd = 10;
obj.style.width = 0 'px';
obj.style.height = 0 'px';
obj.style.display = 'block';
var process = function(width,height){
width = oWidth-widthheight = oHeight-height
if(width !== oWidth || height !== oHeight) {
obj.style.width = width 'px';
obj.style.height = height 'px';
setTimeout(function(){process(width,height);},speed);
}
else {
obj.style.width = oWidth 'px';
obj.style.height = oHeight 'px';
if(fn)fn.call(obj);
}
}
process(0,0);
}
The calling method is as follows:
hide ('a','normal',function(){
show('a','normal');
});
Ugh. . . I feel like it's so redundant, but I don't know how to optimize it. I hope someone can write something more concise. . .