base.js很多面向对象的js实现封装

Object.extend = function (destination, source) {
    for (property in source) {
        destination[property] = source[property];
    }
    return destination;
};
Object.extend(Date.prototype, {
    newDate: function (t) {
        var str = t.split('-');
        var date = new Date();
        date.setUTCFullYear(str[0], str[1] - 1, str[2]);
        date.setUTCHours(0, 0, 0, 0);
        return date
    }
});
Function.prototype.bind = function () {


    var __method = this;
    var args = Array.prototype.slice.call(arguments);
    var object = args.shift();


    return function () {
        return __method.apply(object, args.concat(Array.prototype.slice.call(arguments)));
    };
};


function contains(a, b) {
    try {
        return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition(b) & 16);
    } catch (e) { }


}


var Event = function () {


    function addListener(elem, type, listener) {


        function fun(e) {
            var currentTarget = e.currentTarget,
relatedTarget = e.relatedTarget;


            if (!contains(currentTarget, relatedTarget) && currentTarget != relatedTarget) {
                listener.call(currentTarget, e);
            }
        }


        if (elem.addEventListener) {
            if (type == 'mouseenter') {
                elem.addEventListener('mouseover', fun, false);
            } else if (type == 'mouseleave') {
                elem.addEventListener('mouseout', fun, false);
            } else {
                elem.addEventListener(type, listener, false);
            }
        } else {
            elem.attachEvent('on' + type, listener);
        }
    }


    function trigger(element, event) {


        if (typeof element == "undefined" || element == null) return;
        if (document.createEvent) {


            // 其他标准浏览器使用dispatchEvent方法


            var evt = document.createEvent('HTMLEvents');


            // initEvent接受3个参数:


            // 事件类型,是否冒泡,是否阻止浏览器的默认行为


            evt.initEvent(event, true, true);


            return !element.dispatchEvent(evt);


        }


        else {


            // 低版本IE浏览器支持fireEvent方法


            var evt = document.createEventObject();


            return element.fireEvent('on' + event, evt)






        }


    }


    return {


        addListener: addListener,


        trigger: trigger
    };


}();


var getScroll = function () {
    var t,
    l,
    w,
    h,
    ch,
    oh;
    if (document.documentElement && document.documentElement.scrollTop) {
        t = document.documentElement.scrollTop;
        l = document.documentElement.scrollLeft;
        w = document.documentElement.scrollWidth;
        h = document.documentElement.scrollHeight;
        ch = document.documentElement.clientHeight;
        oh = document.documentElement.offsetHeight
    } else if (document.body) {
        t = document.body.scrollTop;
        l = document.body.scrollLeft;
        w = document.body.scrollWidth;
        h = document.body.scrollHeight;
        ch = document.body.clientHeight;
        oh = document.body.offsetHeight
    }
    return {
        t: t,
        l: l,
        w: w,
        h: h,
        ch: ch,
        oh: oh
    }
};
var Ajax = {


    getScript: function (src, charset, callback) {


        var script = document.createElement('script');
        script.charset = charset;
        script.type = 'text/javascript';
        callback = callback || Function();
        script.onload = script.onreadystatechange = function () {
            var state = script.readyState;
            if (!callback.done && (!state || (state === 'loaded' || state === 'complete'))) {
                callback.done = true;
                callback();
                script.parentNode.removeChild(script);
            }
        };


        script.src = src;
        document.getElementsByTagName('head')[0].appendChild(script);
    },


    JSONP: function (url, callback, charset, jscb) {


        var cb = "cb_" + new Date().getTime();


        url += (url.indexOf("?") == -1 ? "?" : "&") + "cb=" + cb;


        cb = jscb || cb;


        var _head = document.getElementsByTagName('head')[0];


        var _script = document.createElement('script');


        var iscb = false;


        _script.setAttribute('charset', (charset || "gb2312"));


        _script.setAttribute('type', 'text/javascript');


        _script.setAttribute('src', url);


        _head.appendChild(_script);


        window[cb] = function (data) {


            iscb = true;


            callback(data);


            try {


                delete window[cb];
                _head.removeChild(_script);


            } catch (e) {


                window[cb] = null;


            }


        };


        var outtime = 15000;
        if (outtime) {
            setTimeout(function () {
                if (iscb) {
                    return;
                }
                delete window[cb];
                if (_script) {
                    _head.removeChild(_script);
                }
            },
            outtime);
        }
    },


    createXHR: function () {//惰性绑定
        var wxhr = window.XMLHttpRequest ? window.XMLHttpRequest : window.ActiveXObject,
methods = [
function () {
   return new wxhr('MSXML2.XMLHTTP');
},
function () {
   return new wxhr('MSXML2.XMLHTTP.4.0');
},
function () {
   return new wxhr('MSXML2.XMLHTTP.6.0');
},
function () {
   return new wxhr;
}
];


        for (var i = methods.length; i--;) {
            try {
                methods[i]();
                createXHR = methods[i];
                break;
            }
            catch (e) {
            }
        }
        methods = null;
        return createXHR();
    },


    get: function (url, callback, option) {
        var xhr = ajax.createXHR();
        xhr.open("get", url, true);


        xhr.onreadystatechange = function () {
            //readyState为1时读取xhr.status在IE8中未指明的错误。
            if (xhr.readyState == 4 && xhr.status == 200) {
                if (xhr.responseXML.documentElement) {
                    callback(xhr.responseXML);
                } else {
                    var doc = new ActiveXObject("MSxml2.DOMDocument")
                    doc.loadXML(xhr.responseText);
                    callback(doc);
                }
            }
        };


        xhr.send();
    },


    post: function (url, option) {
        var data = option.data;
        var http = Ajax.createXHR();
        var callback = option.callback || Function();
        http.open("POST", url, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        // http.setRequestHeader("Content-length", data.length);
        // http.setRequestHeader("Connection", "close");


        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                callback(http.responseText);
            }
        }


        http.send(data);
    }


};


var AjaxObj =
function () {
    function request(url, opt) {
        function fn() { }
        // var async = opt.async !== true,
        var async = opt.async,
            method = opt.method || 'GET',
            data = opt.data || null,
            success = opt.success || fn,
            failure = opt.failure || fn;
        method = method.toUpperCase();
        if (method == 'GET' && data) {
            url += (url.indexOf('?') == -1 ? '?' : '&') + data;
            data = null;
        }
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        xhr.onreadystatechange = function () {
            _onStateChange(xhr, success, failure);
        };
        xhr.open(method, url, async);
        if (method == 'POST') {
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;');
        }
        xhr.send(data);
        return xhr;
    }
    function _onStateChange(xhr, success, failure) {
        if (xhr.readyState == 4) {
            var s = xhr.status;
            if (s >= 200 && s < 300) {
                success(xhr);
            } else {
                failure(xhr);
            }
        } else { }
    }
    return { request: request };
}();


var Class = new function () {


    function _Base() {


    }


    _Base.prototype = {
        //getElementById
        $: function (o) { return typeof (o) == 'string' ? document.getElementById(o) : o; },
        //createElement
        $C: function (o) { return document.createElement(o); },


        $E: function (e) {
            var tempObj = e && (e.target || e.srcElement) || event.srcElement;
            return tempObj;
        },
        //addEventListener
        $aE: function (elm, evType, fn, useCapture) {
            if (elm.addEventListener) {
                elm.addEventListener(evType, fn, useCapture);
                return true;
            } else if (elm.attachEvent) {
                var r = elm.attachEvent('on' + evType, fn);
                return r;
            } else {
                elm['on' + evType] = fn;
            }
        },
        //removeEventListener
        $dE: function (elm, evType, fn, useCapture) {
            if (elm.removeEventListener) {
                elm.removeEventListener(evType, fn, useCapture);
                return true;
            } else if (elm.detachEvent) {
                var r = elm.detachEvent('on' + evType, fn);
                return r;
            } else {
                elm['on' + evType] = null;
                return;
            }
        },


        $aC: function (obj, name) {
            if (this.isNullorEmpty(this.$(obj).className)) {
                this.$(obj).className = name;
            } else {
                var cname = this.$(obj).className;
                var pattern = new RegExp("(\s*)" + name + "(\s*)", "ig");
                var reg = null;
                if (reg = cname.match(pattern)) {
                    return;
                } else {


                    this.$(obj).className = (cname + " " + name).replace(/\s+/, " ");
                }
            }
        },


        $dC: function (obj, name) {
            if (this.isNullorEmpty(this.$(obj).className)) {
                return;
            } else {
                var cname = this.$(obj).className;
                var pattern = new RegExp("(\s*)" + name + "(\s*)", "ig");
                var reg = null;
                if (reg = cname.match(pattern)) {
                    this.$(obj).className = cname.replace(reg, "");
                } else {
                    return;
                }
            }
        },


        isNullorEmpty: function (obj) {
            if (obj == null || obj == "" || obj == "undefined") return true;
            else return false;
        },


        getPos: function (obj) {


            var curleft = 0;
            var curtop = 0;
            if (obj.offsetParent) {
                do {
                    curleft += obj.offsetLeft;
                    curtop += obj.offsetTop;
                }
                while (obj = obj.offsetParent)
            } else if (obj.x) {
                curleft += obj.x;
                curtop += obj.y;
            }


            return {
                'x': curleft,
                'y': curtop
            };


        },


        trim: function (str) {
            return str.replace(/(^\s*)|(\s*$)/g, "");
        },


        getStyle: function (obj, styleProp) {
            if (obj.currentStyle) return obj.currentStyle[styleProp];
            else if (window.getComputedStyle) return document.defaultView.getComputedStyle(obj, null).getPropertyValue(styleProp);
        },
        $wC : function(name, value, path, domain, expireDay) {
            if (expireDay) {
                var date = new Date();
                date.setTime(date.getTime() + expireDay * 24 * 3600 * 1000);
                document.cookie = name + "=" + escape(value) +
                                ((expireDay) ? "; expires=" + date.toUTCString() : "") +
                                ((domain) ? "; domain=" + domain : "fund.eastmoney.com") +
                                ((path) ? "; path=" + path : "");


            }
            else {
                document.cookie = name + "=" + escape(value) +
                                    ((domain) ? "; domain=" + domain : "fund.eastmoney.com") +
                                    ((path) ? "; path=" + path : "");


            }
        },
        $rC: function (name) {
            var dc = document.cookie;
            var prefix = name + "=";
            var begin = dc.indexOf("; " + prefix);
            if (begin == -1) {
                begin = dc.indexOf(prefix);
                if (begin != 0) {
                    return null
                }
            } else {
                begin += 2
            }
            var end = document.cookie.indexOf(";", begin);
            if (end == -1) {
                end = dc.length
            }
            return unescape(dc.substring(begin + prefix.length, end))
        }
    };


    //exports


    //1 window
    Object.extend(window, _Base.prototype);


    //2 Class
    return {


        create: function () {


            var Base = function () {


                this.initialize.apply(this, arguments);
            }


            Base.prototype = new _Base;
            Base.prototype.initialize = Function();
            return Base;
        }
    };


};


//加载脚本
function script(src, charset, callback) {
    Ajax.getScript(src, charset, callback);
}
(function () {
    //if (typeof HTMLElement !== "undefined" && !("outerHTML" in HTMLElement.prototype)){
    //console.log("defined outerHTML");
    var outerHTML = "outerHTML" in document.createElement("div");
    if (outerHTML || typeof HTMLElement === "undefined") {
        return;
    }
    HTMLElement.prototype.__defineSetter__("outerHTML", function (str) {
        var fragment = document.createDocumentFragment();
        var div = document.createElement("div");
        div.innerHTML = str;


        for (var i = 0, n = div.childNodes.length; i < n; i++) {
            fragment.appendChild(div.childNodes[i]);
        }


        this.parentNode.replaceChild(fragment, this);
    });


    //
    HTMLElement.prototype.__defineGetter__("outerHTML", function () {
        var tag = this.tagName;
        var attributes = this.attributes;
        var attr = [];
        //for(var name in attributes){//遍历原型链上成员
        for (var i = 0, n = attributes.length; i < n; i++) {//n指定的属性个数  
            if (attributes[i].specified) {
                attr.push(attributes[i].name + '="' + attributes[i].value + '"');
            }
        }


        return ((!!this.innerHTML) ?
                 '<' + tag + ' ' + attr.join(' ') + '>' + this.innerHTML + '</' + tag + '>' :
                 '<' + tag + ' ' + attr.join(' ') + '/>');
    });


}());


//activePic 焦点图切换
(function (ns) {


    var activePic = Class.create();


    Object.extend(activePic.prototype, {


        initialize: function (oid, atIndex) {
            this.obj = this.$(oid);
            this.liArr = this.obj.getElementsByTagName("li");
            this.Index = atIndex;
            this.changeTime = 5000;
        },


        init: function () {//初始化
            var _this = this;
            this.olObj = this.$C("ol");
            this.obj.appendChild(this.olObj);
            this.olNum = [];


            for (var i = 0; i < this.liArr.length; ++i) {
                var _numBox = this.$C("span");
                _numBox.index = i;
                _numBox.innerHTML = "<a>" + (i + 1) + "</a>";
                _numBox.onmouseover = function () {
                    _this.goSwitch(this.index);
                };
                _numBox.onmouseout = function () {
                    _this.goon();
                };
                this.liArr[i].onmouseover = function () {
                    _this.pause();
                };
                this.liArr[i].onmouseout = function () {
                    _this.goon();
                };
                this.olObj.appendChild(_numBox);
                this.olNum.push(_numBox);
            }
            this.switchPic(this.Index);
            this.refreshSwitchTimer = setTimeout(function () { _this.reSwitchPic() }, this.changeTime);
        },
        switchPic: function (index) {
            if (index > (this.liArr.length - 1)) index = 0;
            for (var i = 0; i < this.liArr.length; ++i) {
                this.liArr[i].style.zIndex = 10 + i;
            }
            this.liArr[index].style.zIndex = 10 + this.liArr.length;
            this.showSwitchNav(index);
        },
        showSwitchNav: function (index) {
            for (var i = 0; i < this.olNum.length; ++i) {
                this.olNum[i].className = "";
            }
            this.olNum[index].className = "at";
        },
        reSwitchPic: function () {
            clearTimeout(this.refreshSwitchTimer);
            this.refreshSwitchTimer = null;
            this.Index++;
            if (this.Index > (this.liArr.length - 1)) this.Index = 0;
            this.switchPic(this.Index);
            var _this = this;
            this.refreshSwitchTimer = setTimeout(function () { _this.reSwitchPic() }, this.changeTime);
        },
        pause: function () {
            clearTimeout(this.refreshSwitchTimer);
        },
        goon: function () {
            clearTimeout(this.refreshSwitchTimer);
            var _this = this;
            this.refreshSwitchTimer = setTimeout(function () { _this.reSwitchPic() }, this.changeTime);
        },
        goSwitch: function (index) {
            clearTimeout(this.refreshSwitchTimer);
            this.Index = index - 1;
            this.reSwitchPic();
            this.pause();
        }
    });
    ns.activePic = activePic;


})(window);


var addFavor = function (url, title) {
    var _url = url, _title = title;
    if (arguments.length = 0) {
        _url = window.location.href;
        _title = window.document.title;
    }
    try {
        window.external.addFavorite(_url, _title);
    } catch (e) {
        _url = window.location;
        try { window.sidebar.addPanel(_title, _url, ""); }
        catch (e) { alert("加入收藏失败,请使用Ctrl+D进行添加"); }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值