[Javascript] 层控制(隐藏、显示、卷起、展开)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Animate</title>
<script>
(
function(){
if(!window.dk){window['dk']={} }
//根据ID获取对象
function $(){
    if(typeof(arguments[0]) == 'string')
        return document.getElementById(arguments[0]);
    else
        return arguments[0];
   }
window['dk']['$']=$;
//根据Class名称获取对象
function getElementByClassName(){};
window['dk']['getElementByClassName']=getElementByClassName;
//绑定事件
function addEvent(node,type,listener){
    //if(!(node=$(node))){return false;}
    if(node.addEventListener){
        node.addEventListener(type,listener,false);
        return true;
    }
    else if(node.attachEvent){
         node['e'+type+listener]=listener;
        node[type+listener]=function(){
            node['e'+type+listener](window.event);
            }
        node.attachEvent('on'+type,node[type+listener]);
        return true;
    }
    return false;
 }
window['dk']['addEvent']=addEvent;
//移出绑定的事件
function removeEvent(node, type, listener){
    if(node.removeEventListener){
        node.removeEventListener(type,listener,false);
        return true;
    }else if(node.detachEvent){
        node.detachEvent('on' + type, node[type+listener]);
        node[type + listener] = null;
        return true;
    }
    return false;
}
window['dk']['removeEvent'] = removeEvent;
//绑定函数的执行对象
function bind(targetObj,func){
    var args = Array.prototype.slice.call(arguments).slice(2);
    return function() {
        return func.apply(targetObj, args.concat(Array.prototype.slice.call(arguments)));
    }
}
window['dk']['bind']=bind;
//检查childNode是被包含在parentNode中
function contains(parentNode,childNode){
    return parentNode.contains ? parentNode != childNode && parentNode.contains(childNode) : !!(parentNode.compareDocumentPosition(childNode) & 16);
    }
window['dk']['contains']=contains;
//获取Event对象
function getEvent(e){
    return e || window.event;
    }
window['dk']['getEvent']=getEvent;
//停止冒泡
function stopBubble(e){
    getEvent(e).bubbles?getEvent(e).stopPropagation():getEvent(e).cancelBubble=true;
    }
window['dk']['stopBubble']=stopBubble;
//恢复冒泡
function startBubble(e){
    getEvent(e).initEvent?getEvent(e).initEvent():getEvent(e).cancelBubble=false;
    }
window['dk']['startBubble']=startBubble;
//检查mouseover和mouseout模式下取消事件派发
function checkHover(e,target){
    if(dk.getEvent(e).type=="mouseover"){
        return !contains(target,getEvent(e).relatedTarget||getEvent(e).fromElement) && !((getEvent(e).relatedTarget||getEvent(e).fromElement)===target);
        }
    else{
        return !contains(target,getEvent(e).relatedTarget||getEvent(e).toElement) && !((getEvent(e).relatedTarget||getEvent(e).toElement)===target);
        }
    }
window['dk']['checkHover']=checkHover;
//获取事件触发的对象
function getEventTarget(e){
    return dk.getEvent(e).target || dk.getEvent(e).srcElement;
}
window['dk']['getEventTarget']=getEventTarget;
//获取窗口的大小
function getBrowserSize(){
    var de=document.documentElement;
    return {
        (window.innerWidth||(de&&de.clientWidth)||document.body.clientWidth),
        height:(window.innerHeight||(de&&de.clientHeight)||document.body.clientHeight)}
}
window['dk']['getBrowserSize']=getBrowserSize;
//获取对象在页面中的位置
function getPositionInDoc(target){
    (typeof(target) == 'string') && (target = document.getElementById(target));
    var left = 0, top = 0;
    do {
        left += target.offsetLeft || 0;
        top += target.offsetTop || 0;
        target = target.offsetParent;
    }
    while (target);
    return {
        left: left,
        top: top
    };
}
window['dk']['getPositionInDoc'] = getPositionInDoc;
window['dk']['pageDom'] = getPositionInDoc;
//获取鼠标在Document中的位置
function getMousePositionInDoc(e){
    var scrollx, scrolly;
    if (typeof(window.pageXOffset) == 'number') {
        scrollx = window.pageXOffset;
        scrolly = window.pageYOffset;
    }
    else {
        scrollx = document.documentElement.scrollLeft;
        scrolly = document.documentElement.scrollTop;
    }
    return {
        x: e.clientX + scrollx,
        y: e.clientY + scrolly
    }
}
window['dk']['getMousePositionInDoc'] = getMousePositionInDoc;
window['dk']['pageMouse'] = getMousePositionInDoc;
//日志
function myLogs(id){
    id=id||'defaultDebugLogs';
    var logsWindow=null;
    var initWindow=function(){
        logsWindow=document.createElement('ol');
        logsWindow.setAttribute('id',id);
        var winStyle=logsWindow.style;
        winStyle.position='absolute';
        winStyle.top='10px';
        winStyle.right='10px'
        winStyle.width='200px';
        winStyle.height='300px';
        winStyle.border='1px solid #ccc';
        winStyle.background='#fff';
        winStyle.padding=0;
        winStyle.margin=0;
        document.body.appendChild(logsWindow);
    }
    this.writeRow=function(message){
        logsWindow||initWindow();
        var newItem=document.createElement('li');
        newItem.style.padding='2px';
        newItem.style.margin='0 0 1px 0';
        newItem.style.background='#eee';
        if(typeof(message)=='undefined'){
            newItem.innerHTML='<span style="color:#f90;">Message is undefined</span>';
        }
        else{
            newItem.innerHTML=message;
        }
        logsWindow.appendChild(newItem);
    }
}

myLogs.prototype={
    write:function(message){
        
        if(typeof(message) == 'string'&&message.length==0){
            return this.writeRow('<span style="color:#900;">warning:</span> empty message');
        }
        if(typeof(message) != 'string' && typeof(message) != 'undefined'){
            if(message.toString) return this.writeRow(message.toString());
            else return this.writeRow(typeof(message));
        }
        if(typeof(message) == 'undefined'){
            return this.writeRow('<span style="color:#f90;">Message is undefined</span>');
        }
        message=message.replace(/</g,"&lt;").replace(/</g,"&gt;");
        return this.writeRow(message);
    },
    header:function(message){
        
    }
}
window['dk']['logs'] = new myLogs();
//Dom加载完成事件
function ready(loadEvent){
    var init = function(){
        if(arguments.callee.done)
            return;
        arguments.callee.done = true;
        loadEvent.apply(document,arguments);
    }
    
    if(document.addEventListener){
        document.addEventListener('DOMContentLoaded',init,false);
    }
    
    if(/WebKit/i.test(navigator.userAgent)){
        var _timer = setInterval(function(){
            if(/loaded|complete/.test(document.readyState)){
                clearInterval(_timer);
                init();
            }
        },10)
    }
    
    
    /*@if(@_win32)*/
    document.write('<script id=__ie_onload defer src=javascript:void(0)></script>');
    var script = document.getElementById('__ie_onload');
    script.onreadystatechange = function(){
        if(this.readyState == 'complete'){
            init();
        }
    }
    /*@end @*/
    return true;
}
window['dk']['ready'] = ready;
})();

var _$ = function(node){
    if(typeof(node) == 'string'){
        node = dk.$(node);
    }
    this.node= node;
}
_$.prototype = {
    fixover:function(func){
        dk.addEvent(this.node,'mouseover',function(e){
            if(dk.checkHover(e,this)){
                func(e);
            }
        });
        return this;
    },
    fixout:function(func){
        dk.addEvent(this.node,'mouseout',function(e){
            if(dk.checkHover(e,this)){
                func(e);
            }
        })
        return this;
    },
    css:function(styleName){
        if (this.node.currentStyle) {
            var value = this.node.currentStyle[styleName];
            if(value == 'auto' && styleName == 'width'){
                value = this.node.clientWidth;
            }
            if(value == 'auto' && styleName == 'height'){
                value = this.node.clientHeight;
            }
            return value;
        }
        else if (window.getComputedStyle) {
            var value = window.getComputedStyle(this.node, null).getPropertyValue(this.getSplitName(styleName));
            return value;
        }
    },
    getSplitName:function(styleName){
        return styleName.replace(/([A-Z])/g, '-$1').toLowerCase();
    }
}
$$ = function(node){
    return new _$(node);
}
var Tween={
    Linear: function(t,b,c,d){ return c*t/d + b; },
    Quad: {
        easeIn: function(t,b,c,d){
            return c*(t/=d)*t + b;
        },
        easeOut: function(t,b,c,d){
            return -c *(t/=d)*(t-2) + b;
        },
        easeInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return c/2*t*t + b;
            return -c/2 * ((--t)*(t-2) - 1) + b;
        }
    },
    Cubic: {
        easeIn: function(t,b,c,d){
            return c*(t/=d)*t*t + b;
        },
        easeOut: function(t,b,c,d){
            return c*((t=t/d-1)*t*t + 1) + b;
        },
        easeInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return c/2*t*t*t + b;
            return c/2*((t-=2)*t*t + 2) + b;
        }
    },
    Quart: {
        easeIn: function(t,b,c,d){
            return c*(t/=d)*t*t*t + b;
        },
        easeOut: function(t,b,c,d){
            return -c * ((t=t/d-1)*t*t*t - 1) + b;
        },
        easeInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
            return -c/2 * ((t-=2)*t*t*t - 2) + b;
        }
    },
    Back: {
        easeIn: function(t,b,c,d,s){
            if (s == undefined) s = 1.70158;
            return c*(t/=d)*t*((s+1)*t - s) + b;
        },
        easeOut: function(t,b,c,d,s){
            if (s == undefined) s = 1.70158;
            return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
        },
        easeInOut: function(t,b,c,d,s){
            if (s == undefined) s = 1.70158; 
            if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
            return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
        }
    }
}
var Motion=function(target){
    var t = 0;
    var d = 150;
    var delayTime = 10;
    var styles=null;
    var stylesChange={};
    var stylesBegin={};
    var callBackFunc=null;
    var timer=null;
    var quickStylesBefore=null;
    var quickStylesAfter=null;
    var animateStatus=false;
    var funcQueue=[];
    if(typeof(target)=='string')
        target=document.getElementById(target);
    
    this.resetStatus=function(){
        t=0;
        styles=null;
        stylesChange={};
        stylesBegin={};
        callBackFunc=null;
        timer=null;
        quickStylesBefore=null;
        quickStylesAfter=null;
    }
    this.setDelayTime=function(_delayTime){
        delayTime = _delayTime;
    }
    this.setStyles=function(_styles){
        styles=_styles;
    }
    this.setCallBackFunc=function(_callBackFunc){
        callBackFunc=_callBackFunc;
    }
    this.pushFuncToQueue = function(funcString){
        funcQueue.push(funcString);
    }
    this.getAnimateStatus=function(){
        return animateStatus;
    }
    this.setQuickStyle=function(_quickStyles,quickType){
        if(quickType)
            quickStylesBefore = _quickStyles;
        else
            quickStylesAfter = _quickStyles;
    }
    this.getTargetStyle=function(){
        return {target.style.width || target.clientWidth,height:target.style.height || target.clientHeigth}
    }
    var calculatChange=function(){
        for(var styleName in styles){
            stylesChange[styleName]=parseInt(styles[styleName])-parseInt(target.style[styleName] || 0);
            stylesBegin[styleName]=parseInt(target.style[styleName] || 0);
        }
    }
    
    var setTargetStyles=function(_styles){
        for(var styleName in _styles){
            target.style[styleName]=_styles[styleName];
        }
    }
    
    var beforeRun = function(){
        quickStylesBefore && setTargetStyles(quickStylesBefore);
        calculatChange();        
        target.style.display='block';
        animateStatus = true;
    }
    
    this.afterRun = function(){
        if(target.style.width=='0px'||target.style.height=='0px')
            target.style.display='none';
        quickStylesAfter && setTargetStyles(quickStylesAfter);
        if(funcQueue.length>0)
        {
            animateStatus = false;
            var currentFuncArray=funcQueue.shift();
            return currentFuncArray[0].apply(this,currentFuncArray[1]);
        }
            
        animateStatus = false;
        //this.slideDown();
    }
    
    this.run=function(){
        
        (t == 0) && beforeRun();
        for(var styleName in styles){
            target.style[styleName]=Tween.Quad.easeInOut(t,stylesBegin[styleName],stylesChange[styleName],d) + 'px';
        }
        t++;
        if(t<=d)
            return timer = setTimeout(dk.bind(this,this.run),delayTime);
        this.afterRun();
        if(callBackFunc)
            return callBackFunc();
    }
}
Motion.prototype={
    animate : function(styles,callBackFunc){
        if(this.getAnimateStatus())
            return this.pushFuncToQueue([this.animate,arguments]);
        this.resetStatus();
        this.setStyles(styles)
        this.setCallBackFunc(callBackFunc);        
        this.run();
    },
    slideDown:function(callBackFunc){
        if(this.getAnimateStatus())
            return this.pushFuncToQueue([this.slideDown,arguments]);
        this.resetStatus();
        var targetStyle=this.getTargetStyle();
        this.setQuickStyle({height:'0px'},true);
        this.setStyles({height:targetStyle.height});
        this.setCallBackFunc(callBackFunc);
        this.run();
    },
    slideUp:function(callBackFunc){
        if(this.getAnimateStatus())
            return this.pushFuncToQueue([this.slideUp,arguments]);
        this.resetStatus();
        var targetStyle=this.getTargetStyle();
        this.setQuickStyle({height:targetStyle.height},false);
        this.setStyles({height:'0px'});
        this.setCallBackFunc(callBackFunc);
        this.run();
    },
    show:function(callBackFunc){
        this.resetStatus();
        var targetStyle=this.getTargetStyle();
        this.setQuickStyle({'0px',height:'0px'},true);
        this.setStyles({targetStyle.width,height:targetStyle.height});
        this.setCallBackFunc(callBackFunc);
        this.run();
    },
    hide:function(callBackFunc){
        this.resetStatus();
        var targetStyle=this.getTargetStyle();
        this.setQuickStyle({targetStyle.width,height:targetStyle.height},false);
        this.setStyles({'0px',height:'0px'});
        this.setCallBackFunc(callBackFunc);
        this.run();
    }
}
var divA;
window.onload=function(){
    divA=new Motion('myDiv');
}
</script>
</head>
<body>
<div id="myDiv" style="position:absolute;left:0;background:#f00; overflow:hidden;300px; height:500px;display:block;">This is out test content.</div>
<div id="div2" style="position:absolute; right:0; background:#ff0;"><a href="http://www.baidu.com" target="_blank" onclick="alert('a');return false;">Hello</a></div>
<input type="button" id="btn1" value="hide" onclick="divA.animate({'0px'})" style="position:fixed; bottom:0; left:40%;"/>
<input type="button" id="btn2" value="show" onclick="divA.animate({'600px'})" style="position:fixed; bottom:0; left:50%;"/>
<input type="button" id="btn3" value="slideUp" onclick="divA.slideUp()" style="position:fixed; bottom:0; left:60%;"/>
<input type="button" id="btn4" value="slideDown" onclick="divA.slideDown()" style="position:fixed; bottom:0; left:70%;"/>
</body>
</html>

--------------------------------------

欢迎您,进入 我系程序猿 的cnBlog博客。

你不能改变你的过去,但你可以让你的未来变得更美好。一旦时间浪费了,生命就浪费了。

You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.

--------------------------------------

分享到QQ空间  

原文地址:https://www.cnblogs.com/jqmtony/p/3951437.html