JavaScript 总结(前端常用工具类的封装)

前端开发 作者: 2024-08-26 11:15:01
JavaScript (class是ES6的新东西,看着不爽可以变,但主要还是里面的方法) 1. type 类型判断 2. Date 3. Array 4. String 字符串操作 5. Numbe

(class是ES6的新东西,看着不爽可以变,但主要还是里面的方法)

1. type 类型判断

class TypeFn {
    isString (o) { //是否字符串
        return Object.prototype.toString.call(o).slice(8,-1) === 'String'
    }

    isNumber (o) { 是否数字
        
    }

    isBoolean (o) { 是否boolean
        
    }

    isFunction (o) { 是否函数
        
    }

    isNull (o) { 是否为null
        
    }

    isUndefined (o) { 是否undefined
        
    }

    isObj (o) { 是否对象
        
    }

    isArray (o) { 是否数组
        
    }

    isDate (o) { 是否时间
        
    }

    isRegExp (o) { 是否正则
        
    }

    isError (o) { 是否错误对象
        
    }

    isSymbol (o) { 是否Symbol函数
        
    }

    isPromise (o) { 是否Promise对象
        
    }

    isSet (o) { 是否Set对象
        
    }


    isFalse (o) {
        if (o == '' || o == undefined || o == null || o == 'null' || o == 'undefined' || o == 0 || o == false || o == NaN) return true
        false
    }

    isTrue (o) {
        return !this.isFalse(o)
    }

    isIos () {
        var u = navigator.userAgent;
        if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {安卓手机
             return "Android";
            
        } else if (u.indexOf('iPhone') > -1) {苹果手机
             return "iPhone";
            trueif (u.indexOf('iPad') > -1) {iPad
             return "iPad";
            if (u.indexOf('Windows Phone') > -1) {winphone手机
             return "Windows Phone";
            
        }else{
            
        }
    }

    isPC () { 是否为PC端
        var userAgentInfo =var Agents = ["Android","iPhone","SymbianOS","Windows Phone"];
        var flag = ;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                flag = ;
                break;
            }
        }
        return flag;
    }

    browserType(){
        var userAgent = navigator.userAgent; 取得浏览器的userAgent字符串
        var isOpera = userAgent.indexOf("Opera") > -1; 判断是否Opera浏览器
        var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; 判断是否IE浏览器
        var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; 判断是否IE的Edge浏览器  
        var isFF = userAgent.indexOf("Firefox") > -1; 判断是否Firefox浏览器
        var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; 判断是否Safari浏览器
        var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; 判断Chrome浏览器

        if (isIE) {
            var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
            reIE.test(userAgent);
            var fIEVersion = parseFloat(RegExp["$1"]);
            if(fIEVersion == 7) return "IE7"
            if(fIEVersion == 8) return "IE8";
            if(fIEVersion == 9) return "IE9"if(fIEVersion == 10) return "IE10"return "IE7以下"IE版本过低
        }
        if (isIE11) return 'IE11'if (isEdge) return "Edge"if (isFF) return "FF"if (isOpera) return "Opera"if (isSafari) return "Safari"if (isChrome) return "Chrome";
    }

    checkStr (str,type) {
        switch (type) {
            case 'phone':   手机号码
                return /^1[3|4|5|6|7|8][0-9]{9}$/.test(str);
            case 'tel':     座机
                return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/case 'card':    身份证
                return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/case 'pwd':     密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线
                return /^[a-zA-Z]\w{5,17}$/.test(str)
            case 'postal':  邮政编码
                return /[1-9]\d{5}(?!\d)/case 'QQ':      QQ号
                return /^[1-9][0-9]{4,9}$/case 'email':   邮箱
                return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/case 'money':   金额(小数点2位)
                return /^\d*(?:\.\d{0,2})?$/case 'URL':     网址
                return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/case 'IP':      IP
                return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/case 'date':    日期时间
                return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/case 'number':  数字
                return /^[0-9]$/case 'english': 英文
                return /^[a-zA-Z]+$/case 'chinese': 中文
                return /^[\u4E00-\u9FA5]+$/case 'lower':   小写
                return /^[a-z]+$/case 'upper':   大写
                return /^[A-Z]+$/case 'HTML':    HTML标记
                return /<("[^"]*"|'[^']*'|[^'">])*>/default:
                ;
        }
    }

     严格的身份证校验
    isCardID(sId) {
        if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
            alert('你输入的身份证长度或格式错误')
            
        }
        身份证城市
        var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
        if(!aCity[parseInt(sId.substr(0,2))]) { 
            alert('你的身份证地区非法'
        }

         出生日期验证
        var sBirthday=(sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2))).replace(/-/g,"/"),d = new Date(sBirthday)
        if(sBirthday != (d.getFullYear()+"/"+ (d.getMonth()+1) + "/" + d.getDate())) {
            alert('身份证上的出生日期非法' 身份证号码校验
        var sum = 0],codes = "10X98765432"
        var i = 0; i < sId.length - 1; i++) {
            sum += sId[i] * weights[i];
        }
        var last = codes[sum % 11]; 计算出来的最后一位身份证号码
        if (sId[sId.length-1] != last) { 
            alert('你输入的身份证号非法'
        }
        
        
    }
}

2. Date

class DateFn {
    /**
     * 格式化时间
     * 
     * @param  {time} 时间
     * @param  {cFormat} 格式
     * @return {String} 字符串
     *
     * @example formatTime('2018-1-29','{y}/{m}/{d} {h}:{i}:{s}') // -> 2018/01/29 00:00:00
     */
    formatTime(time,cFormat) {
        if (arguments.length === 0) null
        if ((time + '').length === 10) {
            time = +time * 1000var format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'if (typeof time === 'object') {
            date = time
        }  {
            date =  Date(time)
        }

        var formatObj = {
            y: date.getFullYear(),m: date.getMonth() + 1var time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g,(result,key) => {
            var value = formatObj[key]
            if (key === 'a') return ['一','二','三','四','五','六','日'][value - 1]
            if (result.length > 0 && value < 10) {
                value = '0' + value
            }
            return value || 0
        })
         time_str
    }


    *
     * 返回指定长度的月份集合
     * 
     * @param  {time} 时间
     * @param  {len} 长度
     * @param  {direction} 方向:  1: 前几个月;  2: 后几个月;  3:前后几个月  默认 3
     * @return {Array} 数组
     * 
     * @example   getMonths('2018-1-29',1)  // ->  ["2018-1","2017-12","2017-11","2017-10","2017-9","2017-8","2017-7"]
     
    getMonths(time,len,direction) {
        var mm =  Date(time).getMonth(),yy =  Date(time).getFullYear(),direction = isNaN(direction) ? 3 : direction,index = mm;
        var cutMonth = function(index) {
            if ( index <= len && index >= -len) {
                return direction === 1 ? formatPre(index).concat(cutMonth(++index)):
                    direction === 2 ? formatNext(index).concat(cutMonth(++index)):formatCurr(index).concat(cutMonth(++index))
            }
             []
        }
        var formatNext = (i) {
            var y = Math.floor(i/12),m = i%12
            return [yy+y + '-' + (m+1)]
        }
        var formatPre = var y = Math.ceil(i/12),m = i%12
            m = m===0 ? 12 : m
            return [yy-y + '-' + (13 - m)]
        }
        var formatCurr = return [yy-yNext + '-' + (13 - mNext),yy+y + '-' + (m+1 数组去重
        var unique = (arr) {
            if ( Array.hasOwnProperty('from') ) {
                return Array.from( Set(arr));
            }{
                var n = {},r=[]; 
                for(var i = 0; i < arr.length; i++){
                    if (!n[arr[i]]){
                        n[arr[i]] = ; 
                        r.push(arr[i]);
                    }
                }
                 r;
            }
        }
        return direction !== 3 ? cutMonth(index) : unique(cutMonth(index).sort((t1,t2){
            new Date(t1).getTime() -  Date(t2).getTime()
        }))
    }



    *
     * 返回指定长度的天数集合
     * 
     * @param  {time} 时间
     * @param  {len} 长度
     * @param  {direction} 方向: 1: 前几天;  2: 后几天;  3:前后几天  默认 3
     * @return {Array} 数组
     *
     * @example date.getDays('2018-1-29',6) // -> ["2018-1-26","2018-1-27","2018-1-28","2018-1-29","2018-1-30","2018-1-31","2018-2-1"]
     
    getDays(time,diretion) {
        var tt =  Date(time)
        var getDay = (day) {
            var t =  Date(time)
            t.setDate(t.getDate() + day)
            var m = t.getMonth()+1
            return t.getFullYear()+'-'+m+'-'+t.getDate()
        }
        var arr = []
        if (diretion === 1var i = 1; i <= len; i++) {
                arr.unshift(getDay(-i))
            }
        }if(diretion === 2) {
                arr.push(getDay(i))
            }
        }i))
            }
            arr.push(tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate())
            ) {
                arr.push(getDay(i))
            }
        }
        return diretion === 1 ? arr.concat([tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate()]) : 
            diretion === 2 ? [tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate()].concat(arr) : arr
    }


    *
     * @param  {s} 秒数
     * @return {String} 字符串 
     *
     * @example formatHMS(3610) // -> 1h0m10s
     
    formatHMS (s) {
        var str = ''
        if (s > 3600) {
            str = Math.floor(s/3600)+'h'+Math.floor(s%3600/60)+'m'+s%60+'s'if(s > 60) {
            str = Math.floor(s/60)+'m'+s%60+'s'
        }{
            str = s%60+'s' str
    }

    获取某月有多少天
    getMonthOfDay (time) {
        var date = var year = date.getFullYear()
        var mouth = date.getMonth() + 1
        var days

        当月份为二月时,根据闰年还是非闰年判断天数
        if (mouth == 2) {
            days = (year%4==0 && year%100==0 && year%400==0) || (year%4==0 && year%100!=0) ? 28 : 29if (mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth == 12月份为:1,12 时,为大月.则天数为31;
            days = 31其他月份,天数为:30.
            days = 30 days
    }

    获取某年有多少天
    getYearOfDay (time) {
        var firstDayYear = .getFirstDayOfYear(time);
        var lastDayYear = .getLastDayOfYear(time);
        var numSecond = (new Date(lastDayYear).getTime() - new Date(firstDayYear).getTime())/1000;
        return Math.ceil(numSecond/(24*3600));
    }

    获取某年的第一天
    getFirstDayOfYear (time) {
        var year =  Date(time).getFullYear();
        return year + "-01-01 00:00:00";
    }

    获取某年最后一天
    getLastDayOfYear (time) {
        var dateString = year + "-12-01 00:00:00"var endDay = .getMonthOfDay(dateString);
        return year + "-12-" + endDay + " 23:59:59"获取某个日期是当年中的第几天
    getDayOfYear (time) {
        new Date(time).getTime() - 获取某个日期在这一年的第几周
    getDayOfYearWeek (time) {
        var numdays = .getDayOfYear(time);
        return Math.ceil(numdays / 7);
    }


    
}

3. Array

class ArrayFn {
    判断一个元素是否在数组中
    contains (arr,val) {
        return arr.indexOf(val) != -1 ? true : ;
    }


    *
     * @param  {arr} 数组
     * @param  {fn} 回调函数
     * @return {undefined}
     
    each (arr,fn) {
        fn = fn || Function;
        var a = [];
        var args = Array.prototype.slice.call(arguments,1);
        var res = fn.apply(arr,[arr[i],i].concat(args));
            if(res != null) a.push(res);
        }
    }

    *
     * @param  {arr} 数组
     * @param  {fn} 回调函数
     * @param  {thisObj} this指向
     * @return {Array} 
     
    map (arr,fn,thisObj) {
        var scope = thisObj || window;
        var i = 0,j = arr.length; i < j; ++i) {
            var res = fn.call(scope,arr[i],i,);
            ) a.push(res);
        }
         a;
    }


    *
     * @param  {arr} 数组
     * @param  {type} 1:从小到大   2:从大到小   3:随机
     * @return {Array}
     
    sort (arr,type = 1) {
        return arr.sort( (a,b) =>(type) {
                case 1:
                    return a - b;
                case 2return b - a;
                case 3return Math.random() - 0.5 arr;
            }
        })
    }

    去重
    unique (arr) {
        ) ) {
             Set(arr));
        }[]; 
            ){
                n[arr[i]]){
                    n[arr[i]] = ; 
                    r.push(arr[i]);
                }
            }
             r;
        }
         注:上面 else 里面的排重并不能区分 2 和 '2',但能减少用indexOf带来的性能
         正确排重
        if ( Array.hasOwnProperty('from') ) {
            return Array.from(new Set(arr))
        }else{
            var r = [],NaNBol = true
            for(var i=0; i < arr.length; i++) {
                if (arr[i] !== arr[i]) {
                    if (NaNBol && r.indexOf(arr[i]) === -1) {
                        r.push(arr[i])
                        NaNBol = false
                    }
                }else{
                    if(r.indexOf(arr[i]) === -1) r.push(arr[i])
                }
            }
            return r
        }
         
    }

    求两个集合的并集
    union (a,b) {
        var newArr = a.concat(b);
        .unique(newArr);
    }

    求两个集合的交集
    intersect (a,1)">var _this = ;
        a = .unique(a);
        this.map(a,1)">(o) {
            return _this.contains(b,o) ? o : ;
        });
    }

    删除其中一个元素
    remove (arr,ele) {
        var index = arr.indexOf(ele);
        if(index > -1) {
            arr.splice(index,1);
        }
         arr;
    }

    将类数组转换为数组的方法
    formArray (ary) {
        (Array.isArray(ary)) {
            arr = ary;
        }  {
            arr = Array.prototype.slice.call(ary);
        };
        最大值
    max (arr) {
        return Math.max.apply(最小值
    min (arr) {
        return Math.min.apply(求和
    sum (arr) {
        return arr.reduce( (pre,cur) =>return pre + cur
        })
    }

    平均值
    average (arr) {
        this.sum(arr)/arr.length
    }
}

4. String 字符串操作

class StringFn {
    *
     * 去除空格
     * @param  {str}
     * @param  {type} 
     *       type:  1-所有空格  2-前后空格  3-前空格 4-后空格
     * @return {String}
     
    trim (str,type) {
        type = type || 1
        return str.replace(/\s+/g,""return str.replace(/(^\s*)|(\s*$)/g,1)">return str.replace(/(^\s*)/g,1)">case 4return str.replace(/(\s*$)/g,1)"> str;
        }
    }

    *
     * @param  {str} 
     * @param  {type}
     *       type:  1:首字母大写  2:首页母小写  3:大小写转换  4:全部大写  5:全部小写
     * @return {String}
     
    changeCase (str,type) {
        type = type || 4
        return str.replace(/\b\w+\b/g,1)"> (word) {
                    return word.substring(0,1).toUpperCase() + word.substring(1).toLowerCase();

                });
            ).toUpperCase();
                });
            return str.split('').map( (word){
                    if (/[a-z]/.test(word)) {
                         word.toUpperCase();
                    }{
                         word.toLowerCase()
                    }
                }).join('' str.toUpperCase();
            case 5 str.toLowerCase();
             str;
        }
    }


    
        检测密码强度
    
    checkPwd (str) {
        var Lv = 0if (str.length < 6 Lv
        }
        if (/[0-9]/.test(str)) {
            Lv++if (/[A-Z]/if (/[\.|-|_]/ Lv;
    }

    过滤html代码(把<>转换)
    filterTag (str) {
        str = str.replace(/&/ig,"&amp;");
        str = str.replace(/</ig,"&lt;");
        str = str.replace(/>/ig,"&gt;");
        str = str.replace(" ","&nbsp;" str;
    }
}

5. Number

class NumberFn {

    随机数范围
    random (min,max) {
        if (arguments.length === 2return Math.floor(min + Math.random() * ( (max+1) - min ))
        };
        }
        
    }

    将阿拉伯数字翻译成中文的大写数字
    numberToChinese (num) {
        var AA = new Array("零","一","二","三","四","五","六","七","八","九","十"var BB = new Array("","十","百","仟","萬","億","点",1)">var a = ("" + num).replace(/(^0*)/g,"").split("."= ""var i = a[0].length - 1; i >= 0; i--(k) {
                case 0:
                    re = BB[7] + re;
                    if(!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
                        .test(a[0]))
                        re = BB[4] +case 8:
                    re = BB[5] + re;
                    BB[7] = BB[5];
                    k = 0;
                    ;
            }
            if(k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
                re = AA[0] + re;
            if(a[0].charAt(i) != 0)
                re = AA[a[0].charAt(i)] + BB[k % 4] + re;
            k++;
        }

        if(a.length > 1)  加上小数部分(如果有小数部分)
        {
            re += BB[6];
            var i = 0; i < a[1].length; i++)
                re += AA[a[1].charAt(i)];
        }
        if(re == '一十')
            re = "十"if(re.match(/^一/) && re.length == 3)
            re = re.replace("一",1)"> re;
    }

    将数字转换为大写金额
    changeToChinese (Num) {
            判断如果传递进来的不是字符的话转换为字符
            if(typeof Num == "number") {
                Num =  String(Num);
            };
            Num = Num.replace(/,/g,"") 替换tomoney()中的“,”
            Num = Num.replace(/ /g,"") //替换tomoney()中的空格
            Num = Num.replace(/¥/g,1)">替换掉可能出现的¥字符
            if(isNaN(Num)) { 验证输入的字符是否为数字
                alert("请检查小写金额是否正确");
                return "";
            };
            字符处理完毕后开始转换,采用前后两部分分别转换
            var part = String(Num).split("."var newchar = ""小数点前进行转化
            var i = part[0].length - 1; i >= 0; i--) {
                if(part[0].length > 10) {
                    若数量超过拾亿单位,提示
                }
                var tmpnewchar = ""
                var perchar = part[0].charAt(i);
                (perchar) {
                    case "0":
                        tmpnewchar = "零" + tmpnewchar;
                        case "1":
                        tmpnewchar = "壹" +case "2":
                        tmpnewchar = "贰" +case "3":
                        tmpnewchar = "叁" +case "4":
                        tmpnewchar = "肆" +case "5":
                        tmpnewchar = "伍" +case "6":
                        tmpnewchar = "陆" +case "7":
                        tmpnewchar = "柒" +case "8":
                        tmpnewchar = "捌" +case "9":
                        tmpnewchar = "玖" +;
                }
                switch(part[0].length - i - 1:
                        tmpnewchar = tmpnewchar + "元";
                        :
                        if(perchar != 0) tmpnewchar = tmpnewchar + "拾"if(perchar != 0) tmpnewchar = tmpnewchar + "佰"if(perchar != 0) tmpnewchar = tmpnewchar + "仟":
                        tmpnewchar = tmpnewchar + "万"case 6case 7:
                        tmpnewchar = tmpnewchar + "亿"case 9:
                        tmpnewchar = tmpnewchar + "拾"var newchar = tmpnewchar + newchar;
            }
            小数点之后进行转化
            if(Num.indexOf(".") != -1if(part[1].length > 2 alert("小数点之后只能保留两位,系统将自动截断");
                    part[1] = part[1].substr(0,1)">)
                }
                for(i = 0; i < part[1].length; i++) {
                    tmpnewchar = ""
                    perchar = part[1].charAt(i)
                    (perchar) {
                        :
                            tmpnewchar = "零" + tmpnewchar;
                            :
                            tmpnewchar = "壹" +:
                            tmpnewchar = "贰" +:
                            tmpnewchar = "叁" +:
                            tmpnewchar = "肆" +:
                            tmpnewchar = "伍" +:
                            tmpnewchar = "陆" +:
                            tmpnewchar = "柒" +:
                            tmpnewchar = "捌" +:
                            tmpnewchar = "玖" +;
                    }
                    if(i == 0) tmpnewchar = tmpnewchar + "角"if(i == 1) tmpnewchar = tmpnewchar + "分";
                    newchar = newchar + tmpnewchar;
                }
            }
            替换所有无用汉字
            while(newchar.search("零零") != -1)
                newchar = newchar.replace("零零","零");
            newchar = newchar.replace("零亿","亿");
            newchar = newchar.replace("亿万",1)">);
            newchar = newchar.replace("零万","万");
            newchar = newchar.replace("零元","元");
            newchar = newchar.replace("零角",1)">);
            newchar = newchar.replace("零分",1)">if(newchar.charAt(newchar.length - 1) == "元") {
                newchar = newchar + "整"
            }
             newchar;
        }
    
}

6. Http


    let url = 'http://demo.com/api'
    例: 
        ajax({
            url: url,success: function(data) {
    
            }
        })
*/
 ajax(setting){
    设置参数的初始值
    var opts={
        method: (setting.method || "GET").toUpperCase(),1)">请求方式
        url: setting.url || "",1)"> 请求地址
        async: setting.async || true,1)"> 是否异步
        dataType: setting.dataType || "json",1)"> 解析方式
        data: setting.data || "",1)"> 参数
        success: setting.success || function(){},1)"> 请求成功回调
        error: setting.error || function(){}  请求失败回调
 参数格式化
     params_format (obj) {
        var i in obj) {
            str += i + '=' + obj[i] + '&'return str.split('').slice(0,-1).join('')
    }

     创建ajax对象
    var xhr= XMLHttpRequest();

     连接服务器open(方法GET/POST,请求地址, 异步传输)
    if(opts.method == 'GET'){
        xhr.open(opts.method,opts.url + "?" + params_format(opts.data),opts.async);
        xhr.send();
    }{
        xhr.open(opts.method,opts.url,opts.async);
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(opts.data);
    }
    
    
    ** 每当readyState改变时,就会触发onreadystatechange事件
    ** readyState属性存储有XMLHttpRequest的状态信息
    ** 0 :请求未初始化
    ** 1 :服务器连接已建立
    ** 2 :请求已接受
    ** 3 : 请求处理中
    ** 4 :请求已完成,且相应就绪
    
    xhr.onreadystatechange = () {
        if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
            (opts.dataType){
                case "json"var json = JSON.parse(xhr.responseText);
                    opts.success(json);
                    case "xml":
                    opts.success(xhr.responseXML);
                    :
                    opts.success(xhr.responseText);
                    ;
            }
        }
    }

    xhr.onerror = (err) {
        opts.error(err);
    }
}



    let url = 'http://demo.com/api'
    例: 
        fetchHttp(url).
            then( res => {
                console.log(res)
            }).catch( e => {
                console.log(e)
            })
        fetchHttp(url,{
            method: 'POST',})
function fetchHttp(url,setting = {}) {
    设置参数的初始值
    let opts={
        method: (setting.method || 'GET').toUpperCase(),1)">请求方式
        headers : setting.headers  || {},1)"> 请求头设置
        credentials : setting.credentials  ||  设置cookie是否一起发送
        body: setting.body || {},mode : setting.mode  || 'cors',1)"> 可以设置 cors,no-cors,same-origin
        redirect : setting.redirect  || 'follow',1)"> follow,error,manual
        cache : setting.cache  || 'default'  设置 cache 模式 (default,reload,no-cache)
    }
    let dataType = setting.dataType || "json",1)"> 解析方式  
        data = setting.data || ""  参数

     obj) {
            str += `${i}=${obj[i]}&`
        }
        if (opts.method === 'GET') {
        url = url + (data?`?${params_format(data)}`:'')
    }{
        setting.body = data || {}
    }
    new Promise( (resolve,reject) => {
        fetch(url,opts).then( async res => {
            let data = dataType === 'text' ? await res.text() :
                dataType === 'blob' ? await res.blob() : await res.json() 
            resolve(data)
        }).catch( e => {
            reject(e)
        })
    })
}

7. DOM

class DomFn {

    $ (selector){ 
        var type = selector.substring(0,1)">if (type === '#'if (document.querySelecotor)  document.querySelector(selector)
                return document.getElementById(selector.substring(1))
            
        }if (type === '.'if (document.querySelecotorAll)  document.querySelectorAll(selector)
                return document.getElementsByClassName(selector.substring(1))
        }return document['querySelectorAll' ? 'querySelectorAll':'getElementsByTagName'](selector)
        }
    } 

    检测类名
    hasClass (ele,name) {
        return ele.className.match(new RegExp('(\\s|^)' + name + '(\\s|$)'));
    }

    添加类名
    addClass (ele,1)">this.hasClass(ele,name)) ele.className += " " + name;
    }

    删除类名
    removeClass (ele,1)">.hasClass(ele,name)) {
            var reg = );
            ele.className = ele.className.replace(reg,'');
        }
    }

    替换类名
    replaceClass (ele,newName,oldName) {
        .removeClass(ele,oldName);
        .addClass(ele,newName);
    }

    获取兄弟节点
    siblings (ele) {
        console.log(ele.parentNode)
        var chid = ele.parentNode.children,eleMatch = []; 
        ){ 
            if(chid[i] != ele){ 
                eleMatch.push(chid[i]); 
            } 
        } 
         eleMatch;
    }

    获取行间样式属性
    getByStyle (obj,name){
        (obj.currentStyle){
              obj.currentStyle[name];
        }return  getComputedStyle(obj,1)">)[name];
        }
    }
}

8. Storage 储存操作

class StorageFn {
    constructor () {
        this.ls = window.localStorage;
        this.ss = window.sessionStorage;
    }

    -----------------cookie---------------------*/
    设置cookie
    setCookie (name,value,day) {
        var setting = arguments[0if (Object.prototype.toString.call(setting).slice(8,1)">){
             setting) {
                var oDate =  Date();
                oDate.setDate(oDate.getDate() + day);
                document.cookie = i + '=' + setting[i] + ';expires=' + oDate;
            }
        } Date();
            oDate.setDate(oDate.getDate() + day);
            document.cookie = name + '=' + value + ';expires=' + oDate;
        }
        
    }

    获取cookie
    getCookie (name) {
        var arr = document.cookie.split('; 'var arr2 = arr[i].split('='if (arr2[0] == name) {
                return arr2[1];
            }
        }
        return ''删除cookie
    removeCookie (name) {
        this.setCookie(name,-1);
    }


    -----------------localStorage---------------------设置localStorage
    setLocal(key,1)"> setting){
                .ls.setItem(i,JSON.stringify(setting[i]))
            }
        }.ls.setItem(key,JSON.stringify(val))
        }
        
    }

    获取localStorage
    getLocal(key) {
        if (key) return JSON.parse(.ls.getItem(key))
        ;
        
    }

    移除localStorage
    removeLocal(key) {
        .ls.removeItem(key)
    }

    移除所有localStorage
    clearLocal() {
        .ls.clear()
    }


    -----------------sessionStorage---------------------设置sessionStorage
    setSession(key,1)">.ss.setItem(i,1)">.ss.setItem(key,1)">获取sessionStorage
    getSession(key) {
        .ss.getItem(key))
        移除sessionStorage
    removeSession(key) {
        .ss.removeItem(key)
    }

    移除所有sessionStorage
    clearSession() {
        .ss.clear()
    }

    
}

9. Other 其它操作

class OtherFn {

    *
     * [deepClone 深度克隆]
     * @param  {[type]} obj [克隆对象]
     * @return {[type]}     [返回深度克隆后的对象]
     
    deepClone (obj) {
        if (obj === null || typeof obj !== 'object')  obj
        var isType = (obj,type) {
             flag,typeString = Object.prototype.toString.call(obj)
            case 'Array':
                    flag = typeString === '[object Array]'
                    break
                case 'Date':
                    flag = typeString === '[object Date]'
                    case 'RegExp':
                    flag = typeString === '[object RegExp]'
                    :
                    flag =  flag
        }
        var getRegExp = (re) {
            var flags = ''
            if (re.global) flags += 'g'
            if (re.ignoreCase) flags += 'i'
            if (re.multiline) flags += 'm'
             flags
        }

        var _clone = (parent) {
            var child,proto,parents = [],children = []
            if (isType(parent,'Array')) { 对数组做特殊处理
                child = [];
            }  对正则做特殊处理
                child =  RegExp(parent.source,getRegExp(parent));
                if (parent.lastIndex) child.lastIndex = parent.lastIndex;
            }  对Date做特殊处理
                child =  Date(parent.getTime());
            }  {
                 处理对象原型
                proto = Object.getPrototypeOf(parent);
                 利用Object.create切断原型链
                child = Object.create(proto);
            }
             处理循环引用
             parents.indexOf(parent);

            if (index != -1 如果父数组存在本对象,说明之前已经被引用过,直接返回此对象
                 children[index];
            }
            parents.push(parent);
            children.push(child);

             parent) {
                child[i] = _clone(parent[i]);
            }

             child;
        }
         _clone(obj)
    }

    获取网址参数
    getUrlParams(name){
        new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"var r = decodeURI(window.location.search).substr(1).match(reg);
        if(r!=null) return  r[2]; 获取全部url参数,并转换成json对象
    getUrlAllParams (url) {
        var url = url ? url : window.location.href;
        var _pa = url.substring(url.indexOf('?') + 1= {};
        var pos = _arrS[i].indexOf('='if (pos == -1continuevar name = _arrS[i].substring(0));
            _rs[name] = value;
        }
         _rs;
    }

    删除url指定参数,返回url
    delParamsUrl(url,1)">var baseUrl = url.split('?')[0] + '?'var query = url.split('?')[1if (query.indexOf(name)>-1var obj = {}
            var arr = query.split("&") {
                arr[i] = arr[i].split("=");
                obj[arr[i][0]] = arr[i][1];
            };
            delete obj[name];
            var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,"&" url
        } url;
        }
    }

    获取十六进制随机颜色
    getRandomColor () {
        return '#' + ((h) {
            new Array(7 - h.length).join("0") + h;
        })((Math.random() * 0x1000000 << 0).toString(16图片加载
    imgLoadAll(arr,callback){
        var arrImg =var img =  Image();
            img.src = arr[i];
            img.onload = (){
                arrImg.push();
                if (arrImg.length == arr.length) {
                    callback && callback();
                }
            }
        }
    }

    音频加载
    loadAudio(src,callback) {
        var audio =  Audio(src);
        audio.onloadedmetadata = callback;
        audio.src = src;
    }

    DOM转字符串
    domToStirng(htmlDOM){
        var div= document.createElement("div");
        div.appendChild(htmlDOM);
         div.innerHTML
    }

    字符串转DOM
    stringToDom(htmlString){
        );
        div.innerHTML=htmlString;
        return div.children[0];
    }


    *
     * 光标所在位置插入字符,并设置光标位置
     * 
     * @param {dom} 输入框
     * @param {val} 插入的值
     * @param {posLen} 光标位置处在 插入的值的哪个位置
     
    setCursorPosition (dom,val,posLen) {
        var cursorPosition = 0(dom.selectionStart){
            cursorPosition = dom.selectionStart;
        }
        .insertAtCursor(dom,val);
        dom.focus();
        console.log(posLen)
        dom.setSelectionRange(dom.value.length,cursorPosition + (posLen || val.length));
    }

    光标所在位置插入字符
    insertAtCursor(dom,1)"> (document.selection){
            dom.focus();
            sel = document.selection.createRange();
            sel.text = val;
            sel.select();
        }if (dom.selectionStart || dom.selectionStart == '0'){
            let startPos = dom.selectionStart;
            let endPos = dom.selectionEnd;
            let restoreTop = dom.scrollTop;
            dom.value = dom.value.substring(0,startPos) + val + dom.value.substring(endPos,dom.value.length);
            if (restoreTop > 0){
                dom.scrollTop = restoreTop;
            }
            dom.focus();
            dom.selectionStart = startPos + val.length;
            dom.selectionEnd = startPos + val.length;
        }  {
            dom.value += val;
            dom.focus();
        }
    }
}

1. pc-reset PC样式初始化

html {
  line-height: 1.15;
   1 */
  -ms-text-size-adjust: 100%;
   2 
  -webkit-text-size-adjust:*/
}

body {
  margin: 0;
}

article,aside,footer,header,nav,section {
  display: block;
}

h1 {
  font-size: 2em; 0.67em 0;
}

figcaption,figure,main {
  

figure { 1em 40px;
}

hr {
  box-sizing: content-box;
  
  height: 0;
  
  overflow: visible;
  

pre {
  font-family: monospace,monospace;
   1em;
  

a {
  background-color: transparent;
  
  -webkit-text-decoration-skip: objects;
  

abbr[title] {
  border-bottom: none;
  
  text-decoration: underline;
   underline dotted;
  

b,strong {
  font-weight: inherit;
} bolder;
}

code,kbd,samp {

dfn {
  font-style: italic;
}

mark { #ff0;
  color: #000;
}

small { 80%;
}

sub,sup { 75%; 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

audio,video { inline-block;
}

audio:not([controls]) { none;

img {
  border-style: none;
}

svg:not(:root) { hidden;
}

button,input,optgroup,select,textarea { sans-serif;
   visible;
}
  text-transform:*/

[type="reset"],[type="submit"] {
  -webkit-appearance: button;
  

button::-moz-focus-inner,[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner {
  padding:

button:-moz-focusring,[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

fieldset { 0.35em 0.75em 0.625em;
}

legend { border-box;
   inherit;
   table;
  
  max-width: 3 
  white-space: normal;
  

progress { inline-block;
   baseline;
  

textarea { auto;
}

[type="checkbox"],[type="radio"] {

[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button {

[type="search"] { textfield;
  
  outline-offset: -2px;
  

[type="search"]::-webkit-search-cancel-button,[type="search"]::-webkit-search-decoration {

 ::-webkit-file-upload-button {
  font:

details,1)">

menu {

summary { list-item;
}

canvas {

template {

[hidden] { none;
}


 reset 

html,body,h1,h2,h3,h4,h5,h6,div,dl,dt,dd,ul,ol,li,p,blockquote,pre,hr,table,caption,th,td,form,fieldset,legend,button,textarea,menu { border-box;
}

2. Phone-reset

 border-box;
} 禁止选中文本 
  -webkit-user-select:
  user-select: Oswald,'Open Sans',Helvetica,Arial,sans-serif
}


 禁止长按链接与图片弹出菜单 

a,img {
  -webkit-touch-callout:ios android去除自带阴影的样式
  -webkit-tap-highlight-color: rgba(0,0);
}

input[type="text"] { none;
}

3. 公共样式提取


.usn{
    -webkit-user-select:none;
    -moz-user-select:
    -ms-user-select:
    -o-user-select:
    user-select:none;
}
 浮动 
.fl { float: left; }
.fr { right; }
.cf { zoom: 1; }
.cf:after {
    content:".";
    display:block;
    clear:both;
    visibility:hidden;
    height:0;
    overflow:hidden;
}

 元素类型 
.db { display: block; }
.dn { none; }
.di { inline }
.dib {display: inline-block;}
.transparent { opacity: 0 }


文字排版、颜色
.f12 { font-size:12px }
.f14 {14px }
.f16 {16px }
.f18 {18px }
.f20 {20px }
.fb { font-weight:bold }
.fn {normal }
.t2 { text-indent:2em }
.red,a.red { color:#cc0031 }
.darkblue,a.darkblue {#039 }
.gray,a.gray {#878787 }
.lh150 { line-height:150% }
.lh180 {180% }
.lh200 {200% }
.unl { text-decoration:underline; }
.no_unl {none; }
.tl { text-align:
.tc { center; }
.tr {
.tj { justify; text-justify: inter-ideograph; }
.wn {  强制不换行 
    word-wrap:normal;
    white-space:nowrap;
}
.wb {  强制换行 break-word;
    word-break:break-all;
}
.wp {  保持空白序列text-align:left;white-space:pre-wrap;word-wrap:word-break:
.wes {  多出部分用省略号表示,用于一行 nowrap;
    text-overflow:ellipsis;
}
.wes-2 {  适用于webkit内核和移动端  -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; 
.wes-3 { 3;
.wes-4 { 4; hidden;
}

 溢出样式 
.ofh { overflow: hidden; }
.ofs {overflow: scroll; }
.ofa { auto; }
.ofv { visible; }

 定位方式 
.ps {position: static; }
.pr {zoom:1; }
.pa { absolute; }
.pf { fixed; }


 垂直对齐方式 
.vt {vertical-align: top; }
.vm { middle; }
.vb { bottom; }


 鼠标样式 
.csd {cursor: default; }
.csp { pointer; }
.csh { help; }
.csm { move; }

 flex布局 
.df-sb {flex;
    align-items: center;
    justify-content: space-between;
}
.df-sa { space-around;
}

 垂直居中 
.df-c { flex; center;
}
.tb-c {
    text-align:center;table-cell;
    vertical-align:middle;
}
.ts-c {
    position: absolute;
    left: 50%; top:
    transform: translate(-50%,-50%);
}
.ts-mc {right:
    bottom:
    margin: auto;
}

 辅助 
.mask-fixed-wrapper {
    width: 100%; fixed;top:
    background:
    z-index: 999;
}
.bg-cover {
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
}
.bg-cover-all { 100% 100%; center center;
}
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68939.html