多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 兼容blob ``` function createObjectURL (blob) { return window[window.webkitURL ? 'webkitURL' : 'URL']['createObjectURL'](blob); }; ``` ### 是否字符串 > 方式一: ``` export const isString = (str) => { // 如果是还得检测是否有值 typeof str === 'string' && str return typeof str === 'string' } ``` > 方式二: ``` export const isString = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'String' } ``` ### 是否数字 ``` export const isNumber = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Number' } ``` ### 是否boolean ``` export const isBoolean = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean' } ``` ### 是否函数 ``` export const isFunction = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Function' } ``` ### 是否为null ``` export const isNull = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Null' } ``` ### 是否undefined ``` export const isUndefined = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined' } ``` ### 是否对象 ``` export const isObj = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Object' } ``` ### 是否数组 ``` export const isArray = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Array' } ``` ### 是否时间 ``` export const isDate = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Date' } ``` ### 是否正则 ``` export const isRegExp = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp' } ``` ### 是否Symbol函数 ``` export const isSymbol = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol' } ``` ### 是否Promise对象 ``` export const isPromise = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Promise' } ``` ### 是否Set对象 ``` export const isSet = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Set' } export const ua = navigator.userAgent.toLowerCase(); ``` ### 是否是微信浏览器 ``` export const isWeiXin = () => { return ua.match(/microMessenger/i) == 'micromessenger' } ``` ### 是否是移动端 ``` export const isDeviceMobile = () => { return /android|webos|iphone|ipod|balckberry/i.test(ua) } ``` ### 是否是QQ浏览器 ``` export const isQQBrowser = () => { return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i) } ``` ### 是否是爬虫 ``` export const isSpider = () => { return /adsbot|googlebot|bingbot|msnbot|yandexbot|baidubot|robot|careerbot|seznambot|bot|baiduspider|jikespider|symantecspider|scannerlwebcrawler|crawler|360spider|sosospider|sogou web sprider|sogou orion spider/.test(ua) } ``` ### 是否ios ``` export const isIos = () => { var u = navigator.userAgent; if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) { //安卓手机 return false } else if (u.indexOf('iPhone') > -1) {//苹果手机 return true } else if (u.indexOf('iPad') > -1) {//iPad return false } else if (u.indexOf('Windows Phone') > -1) {//winphone手机 return false } else { return false } } ``` ### 是否为PC端 ``` export const isPC = () => { var userAgentInfo = navigator.userAgent; var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"]; var flag = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag; } ``` ``` /** * [getQueryStringArgs 用以解析查询字符串] * @return {[Object]} [一个包含所有参数的对象] */ function getQueryStringArgs(){   //取得查询字符串并去掉开头的“?”   var qs = (location.search.length > 0 ? location.search.substring(1) : ""),   // 保存数据对象   args = {},   // 取得每一项   items = qs.length ? qs.split("&") : [],   item = null,   name = null,   value = null,   // 循环中使用的变量   i = 0,   len = items.length;   //逐个将每一项添加到args对象中   for (i = 0; i<len; i++){     item = items[i].split("=");     name = decodeURIComponent(item[0]);     value = decodeURIComponent(item[1]);     if(name.length){     args[name] = value;     }   }   return args; } /** * [convertToArray 将NodeList转为数组] * @param {[Object]} nodes [一个nodelist对象] * @return {[Object]} [返回一个数组] */ function convertToArray(nodes){   var array = null;   try{     array = Array.prototype.slice.call(nodes,0);//针对非IE浏览器   }catch(ex){     array = new Array();     for(var i = 0, len = nodes.length; i < len; i++){       array.push(nodes[i]);     }   }   return array; } /** * [outputAttributes 遍历元素中的所有属性] * @param {[Object]} element [一个DOM元素对象] * @return {[Object]} [返回一个包含属性名=“属性值”的数组] */ function outputAttributes(element){   var pairs = new Array(),   attrName,   attrValue,   i,   len;   for(i = 0, len = element.attributes.length; i < len; i++){     attrName = element.attributes[i].nodeName;     attrValue = element.attributes[i].nodeValue;     if(element.attributes[i].specified){//确保IE7及更早的版本中,也只会返回特定的属性       pairs.push(attrName + "=\"" + attrValue + "\"");     }   }   return pairs.join(" "); } /** * [loadScript 按需动态加载script文件] * @param {[String]} url [JavaScript文件地址] */ function loadScript(url){   var script = document.createElement("script");   script.type = "text/javascript";   script.src = url;   document.body.appendChild(script); } /** * [loadStyles 按需动态加载css文件] * @param {[String]} url [CSS文件地址] */ function loadStyles(url){   var link = document.createElement("link");   link.rel = "stylesheet";   link.type = "text/css";   link.href = url;   var head = document.getElementsByTagName("head")[0];   head.appendChild(link); } /** * [EventUtil 封装跨浏览器的事件处理工具对象] * @type {Object} */ var EventUtil = { /** * [addHandler 添加事件处理程序] * @param {[Object]} ele [事件绑定dom元素] * @param {[String]} type [事件类型] * @param {[Function]} handler [事件处理函数] */   addHandler: function(ele,type,handler){     if(ele.addEventListener){       ele.addEventListener(type,handler,false);     }else if(ele.atachEvent){       ele.atachEvent('on'+type,handler);     }else{       ele['on'+type] = handler;     }   }, /** * [getEvent 获取事件对象] */   getEvent: function(event){     return event ? event : window.event;   }, /** * [getTarget 获取事件目标] */   getTarget: function(event){     return event.target || event.srcElement;   }, /** * [preventDefault 阻止默认事件] */   preventDefault: function(event){     if(event.preventDefault){       event.preventDefault();     }else{       event.returnValue = false;     }   }, /** * [removeHandler 移除事件处理程序] * @param {[Object]} ele [事件绑定dom元素] * @param {[String]} type [事件类型] * @param {[Function]} handler [事件处理函数] */   removeHandler: function(ele,type,handler){     if(ele.removeEventListener){       ele.removeEventListener(type,handler,false);     }else if(ele.detachEvent){       ele.detachEvent('on'+type,handler);     }else{       ele['on'+type] = null;     }   }, /** * [stopPropagation 阻止事件冒泡] */   stopPropagation: function(event){     if(event.stopPropagation){       event.stopPropagation();     }else{       event.cancelBubble = true;     }   }, /** * [getRelatedTarget 当事件为mouseover和mouseout时才有值,其余事件为null] */   getRelatedTarget: function(event){     if(event.relatedTarget){       return event.relatedTarget;     }else if(event.toElement){       return event.toElement;     }else if(event.fromElement){       return event.fromElement;     }else{       return null;     }   }, /** * [getButton DOM版鼠标事件] * @param {[Object]} event [事件对象] */   getButton: function(event){     if(document.implementation.hasFeature("MouseEvents","2.0")){       return event.button;     }else{     switch(event.button){       case 0:       case 1:       case 3:       case 5:       case 7:         return 0;       case 2:       case 6:         return 2;       case 4:         return 1;       }     }   }, /** * [getWheelDelta 获取鼠标滚轮增值(delta)的方法] */   getWheelDelta: function(event){     if(event.wheelDelta){       return (client.engine.oprea && client.engine.oprea < 9.5 ?         -event.wheelDelta : event.wheelDelta);     }else{       return -event.detail * 40;     }   }, /** * [getCharCode 获取字符编码] */   getCharCode: function(event){     if(typeof event.charCode == "number"){       return event.charCode;     }else{       return event.keyCode;     }   }, /** * [getClipboardText 剪贴板事件,获取剪切内容] */   getClipboardText: function(event){     var clipboardData = (event.clipboardData || window.clipboardData);     return clipboardData.getData("text");   }, /** * [setClipboardText 剪贴板事件,设置剪切内容] */   setClipboardText: function(event, value){     if(event.clipboardData){       return event.clipboardData.setData("text/plain", value);     }else if(window.clipboardData){       return window.clipboardData.setData("text", value);     }   } } /** * [serialize 表单序列化] * @param {[Object]} form [一个表单dom对象] */ function serialize(form){   var parts = [],   field = null,   i,   len,   j,   optLen,   option,   optValue;   for(i = 0, len = form.elements.length; i < len; i++){     field = form.elements[i];     switch(field.type){       case "select-one":       case "select-multiple":         if(field.name.length){           for(j = 0,optLen = field.options.length; j < optLen; j++){             option = field.options[j];             if(option.selected){               optvalue = "";               if(option.hasAttribute){                 optValue = (option.hasAttribute("value") ?                   option.value : option.text);               }else{//兼容IE                 optValue = (option.attributes["value"].specified ?                   option.value : option.text);               }               parts.push(encodeURIComponent(field.name) + "=" +                 encodeURIComponent(optValue));             }           }         }         break;       case undefined: //字段集       case "file": //文件输入       case "submit": //提交按钮       case "reset": //重置按钮       case "button": //自定义按钮         break;       case "radio": //单选按钮       case "checkbox": //多选按钮         if(!field.checked){           break;         }       default:         if(field.name.length){           parts.push(encodeURIComponent(field.name) + "=" +             encodeURIComponent(field.value));         }       }     }   return parts.join("&"); } /** * [trim 去掉字符串中的空格] * @param {[String]} str [需要进行处理的字符串] * @param {[Number]} type [处理的类型] * @return {[String]} [返回去除空格之后的字符串] * 1:所有空格 * 2:前后空格 * 3:前空格 * 4:后空格 */ function trim(str, type){   switch(type){     case 1:       return str.replace(/\s+/g,"");     case 2:       return str.replace(/(^\s*)|(\s$)/g,"");     case 3:       return str.replace(/(^s*)/g,"");     case 4:       return str.replace(/(\s*$)/g,"");     default:       return str;   } } /** * [removeRepeatArray 数组去重] * new Set()是ES6的用法 */ function removeRepeatArray(arr){   return Array.form(new Set(arr)); } /** * [upsetArray 数组顺序打乱] */ function upsetArray(arr){   return arr.sort(function(){     return Math.random() - 0.5;   }) } /** * [MaxArray 数组最大值] */ function MaxArray(arr){   return Math.max.apply(null,arr); } /** * [MinArray 数组最小值] */ function MinArray(arr){   return Math.min.apply(null,arr); } /** * 这一块的封装,主要是针对数字类型的数组 * [sumArr 数组求和] */ function sumArray(arr){   var sum=0;   for(var i = 0, len = arr.length; i < len; i++){     sum += arr[i];   }   return sum; } /** * [averageArr 求数组的平均值] */ function averageArray(arr){   var sum = sumArray(arr);   var average = sum/arr.length;   return average; } /** * [randomOne 数组中随机取一个元素] */ function randomOne(arr) {   return arr[Math.floor(Math.random() * arr.length)]; } /** * [getEleCount 返回数组(字符串)一个元素出现的次数] * @param {[type]} obj [可以是一个字符串也可以是一个数组] * @param {[type]} ele [某个元素] * getEleCount('asd56+asdasdwqe','a') * //3 * getEleCount([1,2,3,4,5,66,77,22,55,22],22) * //2 */ function getEleCount (obj, ele) {   var num = 0;   for (var i = 0, len = obj.length; i < len; i++) {     if (ele == obj[i]) {       num ++;     }   }   return num; } /** * [getCount 返回数组(字符串)出现最多次数的元素和它出现次数] * @param {[type]} arr [处理的数组] * @param {[type]} rank,ranktype [rank->长度,默认为数组长度,ranktype,排序方式,默认降序] */ function getCount(arr, rank,ranktype){   var obj = {},   i,   len,   k,   arr1 = [];   //记录每一元素出现的次数   for (i = 0, len = arr.length; i < len; i++) {     k = arr[i];     if (obj[k]) {       obj[k]++;     }     else {       obj[k] = 1;     }   }   //保存结果{el-'元素',count-出现次数}   for (var o in obj) {     arr1.push({el: o, count: obj[o]});   }   //排序(降序)   arr1.sort(function (n1, n2) {     return n2.count - n1.count;   });   //如果ranktype为1,则为升序,反转数组   if(ranktype === 1){     arr1 = arr1.reverse();   }   var rank1 = rank || arr1.length;   return arr1.slice(0,rank1); } /** * [getArrayNum 得到n1-n2下标的数组] * 不传第二个参数,默认返回从n1到数组结束的元素 * @param {[Array]} arr [传入的数组] * @param {[Number]} n1 [开始的位置] * @param {[Number]} n2 [结束的位置] */ function getArrayNum(arr,n1,n2){   var arr1 = [],   len = n2 || arr.length - 1;   for(var i = n1; i <= len; i++){     arr1.push(arr[i]);   }   return arr1; } /** * [removeArrayForValue 筛选数组] * //removeArrayForValue(['test','test1','test2','test','aaa'],'test','%') * //["aaa"] 带有'test'的都删除 * //removeArrayForValue(['test','test1','test2','test','aaa'],'test') * //["test1", "test2", "aaa"] //数组元素的值全等于'test'才被删除 * @param {[type]} arr [传入的数组] * @param {[type]} val [要删除的值] * @param {[type]} type [是不是全等于value] */ function removeArrayForValue(arr,val,type){   arr.filter(function(item){     return type === '%' ? item.indexOf(val) !== -1 : item !== val;   }); } /** * [checkPwd 检测密码强度] * @param {[String]} str [要检测的密码字符串] */ function checkPwd(str) {   var nowLv = 0;   if (str.length < 6) {     return nowLv;   }   if (/[0-9]/.test(str)) {     nowLv++;   }   if (/[a-z]/.test(str)) {     nowLv++;   }   if (/[A-Z]/.test(str)) {     nowLv++;   }   if (/[\.|-|_]/.test(str)) {     nowLv++;   }   return nowLv; } /** * [repeatStr 字符串循环复制] * @param {[String]} str [传入的字符串] * @param {[Number]} count [需要循环复制的次数] */ function repeatStr(str, count) {   var text = '';   for (var i = 0; i < count; i++) {     text += str;   }   return text; } /** * [changeCase 字母大小写切换] * 1:首字母大写 * 2:首页母小写 * 3:大小写转换 * 4:全部大写 * 5:全部小写 * @param {[String]} str [传入的字符串] * @param {[Number]} type [切换的类型] */ function changeCase(str,type){   function ToggleCase(str) {     var itemText = ""     str.split("").forEach(       function (item) {         if (/^([a-z]+)/.test(item)) {           temText += item.toUpperCase();         }         else if (/^([A-Z]+)/.test(item)) {           itemText += item.toLowerCase();         }         else{           itemText += item;         }       });     return itemText;   }     switch (type) {     case 1:       return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {         return v1.toUpperCase() + v2.toLowerCase();       });     case 2:       return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {         return v1.toLowerCase() + v2.toUpperCase();       });     case 3:       return ToggleCase(str);     case 4:       return str.toUpperCase();     case 5:       return str.toLowerCase();     default:       return str;     }   } ```