直接上代码:

v1.4

;
var Tool = (function(){
    var def = {
    };
    //在原型添加方法原始方法
    Function.prototype.method = function(name,func){
        if(!this.prototype[name]){
            this.prototype[name] = func;
        }
    };
    //继承工具
    function extendDeep() {
        var i,
            target = arguments[0] || {},
            astr = '[object Array]',
            toStr = Object.prototype.toString,
            yArr = Array.prototype.slice.call(arguments, 1);
        for (i = 0, len = yArr.length; i < len; i++) {
            var temp = yArr[i];
            for (var j in temp) {
                if (target.hasOwnProperty(j) && (target[i] === temp[i])) {
                    continue;
                }
                if (temp.hasOwnProperty(j)) {
                    if (typeof temp[j] === 'object') {
                        target[j] = (toStr.call(temp[j] === astr)) ? [] : {};
                        extendDeep(target[j], temp[j]);
                    } else {
                        if (typeof temp[j] !== 'undefined') {
                            target[j] = temp[j];
                        }
                    }
                }
            }
        }
        return target;
    }
    /**
     * [showError 报出异常]
     * @param  {[string]} str [异常文本信息]
     * @return {[type]}     [description]
     */
    function showError(str){
        throw new Error(str);
    }

    /*
        原型扩展区
     */ 
    //数组的indexof
    Array.method('indexOf',function(item){
        var i = 0,
            len = this.length;
        for(;i < len;i++){
            if(this[i] === item){
                return i;
            }
        }
        return -1;
    })
    //兼容性判断forEach
    Array.method('forEach',function(callback){
        if(this.forEach){
            this.forEach(function(item){
                callback(item);
            })
        }else {
            for(var i =0,len=this.length;i<len;i++){
                callback(this[i]);
            }
        }
    })
    // 原型
    var Tool = function(){
        if(!(this instanceof Tool)){
            return new Tool();
        }
    };  
    //dom操作
    var dom = {
        //异步加载js
        requireJs : function(url,callback){
            if(!url){
                showError('异步加载的url地址不正确');
            }
            var newJs = document.createElement('script');
            newJs.onreadystatechange = function(){
                if(newJs.readyState === 'loaded' || newJs.readyState === 'complete'){
                    newJs.onreadystatechange = null;
                    callback && callback();
                }
            }
            newJs.onload = function(){
                callback && callback();
            }
            newJs.src = url;
            document.documentElement.firstChild.appendChild(newJs);
        },
        //异步加载css
        requireCss : function(url,callback){
            if(!url){
                showError('异步加载的url地址不正确');
            }
            if(document.createStyleSheet){
                document.createStyleSheet(url);
                callback && callback();
            }else {
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = url;
                callback && callback();
                document.documentElement.firstChild.appendChild(link);

            }
        },
        //下一个兄弟元素
        nextB : function(el){
            return (el.nextElementSibling) ? el.nextElementSibling : el.nextSibling;
        },
        //上一个兄弟元素
        prevB : function(el){
            return (el.previousElementSibling) ? el.previousElementSibling : el.previousSibling;
        },
        // 本身后面的所有兄弟元素,不包括本身
        nextBs : function(el){
            var arr = [],
                curr = this.nextB(el);
                while(curr && curr.nodeType === 1){
                    arr.push(curr);
                    curr = this.nextB(curr);
                }
            return arr;
        },
        // 本身前面的所有兄弟元素,不包括本身
        prevBs : function(el){
            var arr = [],
                curr = this.prevB(el);
            while(curr && curr.nodeType === 1){
                arr.push(curr);
                curr = this.prevB(curr);
            }
            return arr;
        }
    };
    // 数组扩展
    var arr = {
        //是否包含指定元素
        contains : function(target,item){
            return target.indexOf(item) > -1;
        },
        //在参数1中删除参数2指定位的元素返回布尔
        removeAt : function(target,index){
            return !!target.splice(index,1).length;
        },
        //在参数1中删除参数2返回布尔
        remove : function(target,item){
            var index = target.indexOf(item);
            return index > -1 ? this.removeAt(target,index) : false;
        },
        //打乱数组返回新数组
        shuffle : function(target){
            var temp = target,
                j,
                x,
                i = target.length;
            for(;i>0;j = parseInt(Math.random()*i),x = target[--i],target[i] = target[j],target[j] = x){

            }
            return temp;
            //target.sort(function(){return 0.5 - Math.random()});
        },
        //在数组中随机取一个
        random : function(target){
            return target[Math.floor(Math.random() * target.length)];
        },
        // 数组去重
        unique : function(target){
            var temp = [];
            _that: for(var i = 0,len = target.length;i < len;i ++){
                for(var j = i + 1;j < len;j++){
                    if(target[i] === target[j]){
                        continue _that;
                    }
                }
                temp.push(target[i])
            }
            return temp;
        },
        //去除数组中的undefined和Null
        compact : function(target){
            if(!type.isArray(target)){
                throw new Error('target error type');
            }
            return target.filter(function(item){
                return item != undefined;
            })
        },
        //获取数组对象中的属性值,组合成新数组
        pluck : function(target,name){
            var result = [],
                temp;
            target.forEach(function(item){
                temp = item[name];
                if(temp != null){
                    result.push(temp);
                }
            });
            return result;
        },
        //2个数组的并集
        union : function(t1,t2){
            return this.unique(t1.concat(t2));
        },
        // 取2个数组的交集
        intersect : function(t1,t2){
            return t1.filter(function(item){
                return ~t2.indexOf(item);
            });
        },
        //取差集
        diff : function(t1,t2){
            var r = t1;
            for(var i=0;i<t1.length;i++){
                for(var j=0;j<t2.length;j++){
                    if(r[i] === t2[j]){
                        r.splice(i,1);
                        i--;
                        break;
                    }
                }
            }
            return r;
        },
        // 
        max : function(target){
            return Array.max.apply(0,target);
        },
        //min
        min : function(target){
            return Array.min.apply(0,target);
        }
    };
    // 字符串扩展
    var str = {
        // 去空格
        trim : function(str){
            str = str.replace(/^\s+/,'');
            for(var i =str.length - 1;i >=0;i--){
                if(/\S/.test(str.charAt(i))){
                    str = str.slice(0,i + 1);
                    break;
                }
            }
            return str;
        },
        // 模仿C语言print方法
        print : function(str,object){
            var arr = [].slice.call(arguments,1),
                index;
            return str.replace(/#{([^{}]+)}/gm,function(match,name){
                index = Number(name);
                if(index >= 0){
                    return arr[index];
                }
                if(object && object[name] !== ''){
                    return object[name];
                }
                return '';
            })
        },
        //补零
        fillZero :function(target,n){
            var z = new Array(n).join('0'),
                str = z + target,
                result = str.slice(-n);
            return result;
            //return (Math.pow(10,n) + '' + target).slice(-n);
        },
        // 去掉script内部的html标签
        stripTags : function(target){
            if(type.getType(target) === 'String'){
                return target.replace(/<script[^>]*>(\S\s*?)<\/script>/img,'').replace(/<[^>]+>/g,'');
            }
        },
        //首字母大写
        capitalize : function(target){
            return target.charAt(0).toUpperCase() + target.slice(1).toLowerCase();
        },
        //把字符串中的_转成-
        dasherize : function(target){
            return this.underscored(target).replace(/_/g,'-');
        },
        // 把驼峰转换成_
        underscored : function(target){
            return target.replace(/([a-z0-9])([A-Z])/g,'$1_$2').toLowerCase();
        },
        //_ - 转驼峰命名
        camelize: function(target) {
            if (target.indexOf('-') < 0 && target.indexOf('_') < 0) {
                return target;
            }
            return target.replace(/[-_][^-_]/g, function(match) {
                console.log(match)
                return match.charAt(1).toUpperCase();
            })
        },
        //字符串截断方法 目标 长度默认30,截断后符号默认...
        truncate: function(target, len, truncation) {
            len = len || 30;
            truncation = truncation ? truncation : '...';
            return (target.length > len) ? target.slice(0, (len - truncation.length)) + truncation : target.toString();
        },
        //获得字符串字节长度 参数2 utf-8 utf8 utf-16 utf16
        byteLen: function(str, charset) {
            var target = 0,
                charCode,
                i,
                len;
            charset = charset ? charset.toLowerCase() : '';
            if (charset === 'utf-16' || charset === 'utf16') {
                for (i = 0, len = str.length; i < len; i++) {
                    charCode = str.charCodeAt(i);
                    if (charCode <= 0xffff) {
                        target += 2;
                    } else {
                        target += 4;
                    }
                }
            } else {
                for (i = 0, len = str.length; i < len; i++) {
                    charCode = str.charCodeAt(i);
                    if (charCode <= 0x007f) {
                        target += 1;
                    } else if (charCode <= 0x07ff) {
                        target += 2;
                    } else if (charCode <= 0xffff) {
                        target += 3;
                    } else {
                        target += 4;
                    }
                }
            }
            return target;
        },
        //重复item,times次
        repeat: function(item, times) {
            var s = item,
                target = '';
            while (times > 0) {
                if (times % 2 == 1) {
                    target += s;
                }
                if (times == 1) {
                    break;
                }
                s += s;
                times = times >> 1;
            }
            return target;
            //retrun new Array(times).join(item)
        },
        //参2是参1的结尾么?参数3忽略大小写
        endsWith: function(target, item, ignorecase) {
            var str = target.slice(-(item.length));
            return ignorecase ? str.toLowerCase() === item.toLowerCase() : str === item;
        },
        //参数2是参数1的开头么?参数3忽略大小写
        startsWith: function(target, item, ignorecase) {
            var str = target.slice(0, item.length);
            return ignorecase ? str.toLowerCase() === item.toLowerCase() : str === item;
        },
        // 类名中,参数1 是否包含参数2,类名中的分隔符
        containsClass: function(target, item, separator) {
            return separator ? (separator + target + separator).indexOf(separator + item + separator) > -1 : this.contains(target, item);
        },
        //判定一个字符串是否包含另一个字符串
        contains: function(target, item) {
            return target.indexOf(item) != -1;
            //return target.indexOf(item) > -1;
        }
    };
    // 数字扩展
    var num = {};
    // 类型扩展
    var type = {
        getType : function(ele){
            if(!ele)return undefined;
            if(window == document && document != window){
                return 'window';
            }else if(ele.nodeType === 9){
                return 'document';
            }else if(ele.callee){
                return 'arguments';
            }else if(isFinite(ele.length) && ele.item){
                return 'nodeList';
            } else {
                var temp = Object.prototype.toString.call(ele),
                    reg = /\[object (.*)\]/,
                    arr = reg.exec(temp);
                return arr[1].toLowerCase();
            }
        },
        isArray : function(ele){
            return (this.getType(ele) === 'array') ? true : false;
        },
        isFunction : function(ele){
            return (this.getType(ele) === 'function') ? true : false;
        },
        isObject : function(ele){
            return (this.getType(ele) === 'object') ? true : false;
        },
        isString : function(ele){
            return (this.getType(ele) === 'string') ? true : false;
        },
        isNumber : function(ele){
            return (this.getType(ele) === 'number') ? true : false;
        },
        isBoolen : function(ele){
            return (this.getType(ele) === 'boolean') ? true : false;
        },
        isUndefined : function(ele){
            return (this.getType(ele) === 'undefined') ? true : false;
        },
        isNull : function(ele){
            return (this.getType(ele) === 'null') ? true : false;
        }
    };
    // 时间扩展
    var time = {};
    // 获取扩展
    var get = {};

    //样式相关
    var css = {};

    // cookie相关
    var cookie = {};
    //浏览器判断
    var os = {}
    //静态对照表数组
    var objArr = [['dom','arr','str','num','type','time','get','cookie'],[dom,arr,str,num,type,time,get,cookie]]

    //模块的按需加载
    var config = {
        //加载模块
        init :function(name){
            if(name === undefined){
                for(var i=0,len=objArr[0].length;i<len;i++){
                    Tool.prototype[objArr[0][i]] = objArr[1][i];
                }
            }else {
                var _index = objArr[0].indexOf(name);
                Tool.prototype[name] = (_index !== -1) ? objArr[1][_index] : undefined;
                return this;
            }
        },
        //移除模块
        remover : function(name){
            Tool.prototype[name] = undefined;
        },
        //dom文档加载完毕,等同于$(),参数为回调函数
        domReady : function(callback){
            if(document.addEventListener){
                document.addEventListener('DOMContentLoaded',function(){
                    callback && callback();
                },false)
            }else {
                try{
                    document.documentElement.doScroll('left');
                }catch(e) {
                    setTimeout(arguments.callee,50);
                }
                callback && callback();
            }
        },
        extend : function(obj){
            extendDeep(Tool.prototype,obj)
        }
    }
        extendDeep(Tool.prototype,config);
        return Tool;
    })();

zasqw2222
132 声望2 粉丝

苦苦的慢慢的爬行!