const md = { empty:(val)=>{ if(val.length==0||val.replace(/\s/g, "").length==0||!val){ return true } // if(isNull(val)||typeof val=='object'&&Object.keys(val).length === 0|| typeof val != "undefined" ){ // } }, /** * @removeSpace 检查图片是否存在 * imgUrl 图片链接 */ checkImg: (imgUrl) => { if(imgUrl.length<0){ return false } var ImgObj = new Image(); ImgObj.src = imgUrl; console.log(ImgObj,(ImgObj.width > 0 && ImgObj.height > 0)) if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) { return true; } else { return false; } }, /** * @removeSpace 去空格 * value 需要清除空格的字符串 */ removeSpace: (value) => { return value.replace(/\s+/g, ""); }, /** * @dedupe 数组去重 * array 数组 */ dedupe: (array) => { return Array.from(new Set(array)) }, /** * @dedupe 对象去重 * obj 对象 */ dedupeObject: (obj) => { let uniques = []; let stringify = {}; for (let i = 0; i < obj.length; i++) { let keys = Object.keys(obj[i]); keys.sort(function(a, b) { return (Number(a) - Number(b)); }); let str = ''; for (let j = 0; j < keys.length; j++) { str += JSON.stringify(keys[j]); str += JSON.stringify(obj[i][keys[j]]); } if (!stringify.hasOwnProperty(str)) { uniques.push(obj[i]); stringify[str] = true; } } uniques = uniques; return uniques; }, /**@unique * 去重 * arr 数组 */ unique: (arr) => { if (Array.hasOwnProperty('from')) { return Array.from(new Set(arr)); } else { var n = {}, r = []; for (var i = 0; i < arr.length; i++) { if (!n[arr[i]]) { n[arr[i]] = true; r.push(arr[i]); } } return r; } }, /** * @getProperty 获取&设置元素属性 * el html元素 * name html元素属性名称 * val html元素属性名称的值 */ getProperty: (el, name, val) => { const prefix = 'data-' name = prefix + name if (val) { return el.setAttribute(name, val) } else { return el.getAttribute(name) } }, /** * @hasClass 判断是否已存在class * el html元素 * className html class名称 */ hasClass: (el, className) => { let reg = new RegExp('(^|\\s)' + className + '(\\s|$)') return reg.test(el.className) }, /** * @addClass 添加class * el html元素 * className html class名称 */ addClass: (el, className) => { if (this.hasClass(el, className)) { return } let newClass = el.className.split(' ') newClass.push(className) el.className = newClass.join(' ') }, /** * @getHost 获取域名主机 * url 当前页面地址 * className html class名称 */ getHost: (url) => { let host = "null"; if (typeof url == "undefined" || null == url) { url = window.location.href; } let regex = /^\w+\:\/\/([^\/]*).*/; let match = url.match(regex); if (typeof match != "undefined" && null != match) { host = match[1]; } return host; }, /** * @cutstr 截取字符串长度多余用....代替 * str 字符串 * len 需要长度 */ cutstr: (str, len) => { let temp; let icount = 0; let patrn = /[^\x00-\xff]/; let strre = ""; for (let i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr(i, 1); if (patrn.exec(temp) == null) { icount = icount + 1; } else { icount = icount + 2; } strre += temp; } else { break } } return strre + "..."; }, /**@fun_date * 获取时间区间 * num 为负数就是日期往前,正数日期往后 */ fun_date: (num) => { let date1 = new Date(); //今天时间 let time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate() let date2 = new Date(date1); date2.setDate(date1.getDate() + num); //num是正数表示之后的时间,num负数表示之前的时间,0表示今天 let time2 = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate(); return { start: time1, end: time2 }; }, /**@isMobile * 获取手机;类型 *callback 判断手机&电脑后的操作 type: function */ isMobile: (callback) => { let isMobile1 = { Android: function() { return navigator.userAgent.match(/Android/i) ? true : false; }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i) ? true : false; }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false; }, Windows: function() { return navigator.userAgent.match(/IEMobile/i) ? true : false; }, any: function() { return (isMobile1.Android() || isMobile1.BlackBerry() || isMobile1.iOS() || isMobile1 .Windows()); } }; callback(isMobile1) }, /**@decimal * 增加小数点后 * num 修改数值 type: number * digit 增加小数后几位 type: number */ decimal: (num, digit) => { if (parseInt(num) !== parseFloat(num)) { return num } if (typeof num == 'number') { num = num || 0; let f = num.toFixed(digit); return f } else { // console.error('请输入数值') let f = 0; return f.toFixed(digit) } }, /**@timeTrans * 时间转换 * time 时间 type: time * format 时间类型 type: String ('Y/M/D h:m:s') */ timeTrans: ({ time, format }) => { let timer = time || new Date(); let date = new Date(timer); let obj = { Y: '', M: '', D: '', h: '', m: '', s: '' } obj.Y = date.getFullYear(); obj.M = date.getMonth() + 1; obj.M = obj.M < 10 ? "0" + obj.M : obj.M; obj.D = date.getDate(); obj.D = obj.D < 10 ? "0" + obj.D : obj.D; obj.h = date.getHours(); obj.h = obj.h < 10 ? "0" + obj.h : obj.h; obj.m = date.getMinutes(); obj.m = obj.m < 10 ? "0" + obj.m : obj.m; obj.s = date.getSeconds(); obj.s = obj.s < 10 ? "0" + obj.s : obj.s; if (format) { let str = ''; for (let index in format) { str += `${obj[format[index]] || format[index]}`; } return str; } else { return `${obj.Y}-${obj.M}-${obj.D}` } }, /**@injectScript * 动态引入js * src 引入地址 url */ injectScript: (src) => { const s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src; const t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s, t); }, /**@download * 根据url地址下载 * src 地址 url */ download: (url) => { var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; if (isChrome || isSafari) { var link = document.createElement('a'); link.href = url; if (link.download !== undefined) { var fileName = url.substring(url.lastIndexOf('/') + 1, url.length); link.download = fileName; } if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true; } } if (url.indexOf('?') === -1) { url += '?download'; } window.open(url, '_self'); return true; }, /**@getScrollPosition * 获取滚动的坐标 */ getScrollPosition: (el = window) => ({ x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop }), /**@scrollToTop * 滚动到顶部 */ scrollToTop: () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(this.scrollToTop); window.scrollTo(0, c - c / 8); } }, /**@elementIsVisibleInViewport * el是否在视口范围内 * el 为div视图 */ elementIsVisibleInViewport: (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }, /**@shuffle * 洗牌算法随机 * arr 需要随机排序的数组 */ shuffle: (arr) => { var result = [], random; while (arr.length > 0) { random = Math.floor(Math.random() * arr.length); result.push(arr[random]) arr.splice(random, 1) } return result; }, /**@copyTextToClipboard * 劫持粘贴板 * value */ copyTextToClipboard: (value) => { var textArea = document.createElement("textarea"); textArea.style.background = 'transparent'; textArea.value = value; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); } catch (err) { console.log('Oops, unable to copy'); } document.body.removeChild(textArea); }, /**@random * 随机数范围 * min 最小的数 * max 最大的数 */ random: function(min, max) { if (arguments.length === 2) { return Math.floor(min + Math.random() * ((max + 1) - min)) } else { return null; } }, /**@numberToChinese * 将阿拉伯数字翻译成中文的大写数字 * num 数字 */ numberToChinese: (num) => { var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"); var BB = new Array("", "十", "百", "仟", "萬", "億", "点", ""); var a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = ""; for (var i = a[0].length - 1; i >= 0; i--) { switch (k) { case 0: re = BB[7] + re; break; case 4: if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$") .test(a[0])) re = BB[4] + re; break; case 8: re = BB[5] + re; BB[7] = BB[5]; k = 0; break; } 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]; for (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("一", ""); return re; }, /**@contains * 判断一个元素是否在数组中 * arr 数组 * val 元素 */ contains: (arr, val) => { return arr.indexOf(val) != -1 ? true : false; }, /**@sort * 数组排序 * {type} 1:从小到大 2:从大到小 3:随机 * arr 数组 */ sort: (arr, type) => { return arr.sort((a, b) => { switch (type) { case 1: return a - b; case 2: return b - a; case 3: return Math.random() - 0.5; default: return arr; } }) }, /**@union * 两个集合的并集 * a, b 数组 */ union: function(a, b) { var newArr = a.concat(b); return this.unique(newArr); }, /**@intersect * 求两个集合的交集 * a, b 数组 */ intersect: (a, b) => { var _this = this; a = this.unique(a); return this.map(a, function(o) { return _this.contains(b, o) ? o : null; }); }, /**@removearr * 删除其中一个元素 * ele 元素 * arr 数组 */ removearr: (arr, ele) => { var index = arr.indexOf(ele); if (index > -1) { arr.splice(index, 1); } return arr; }, /**@formArray * 将类数组转换为数组 * ary 类数组 */ formArray: (ary) => { var arr = []; if (Array.isArray(ary)) { arr = ary; } else { arr = Array.prototype.slice.call(ary); }; return arr; }, /**@max * 数组中最大值 * arr 数组 */ max: (arr) => { return Math.max.apply(null, arr); }, /**@min * 数组中最小值 * arr 数组 */ min: (arr) => { return Math.min.apply(null, arr); }, /**@sum * 数组中 和 * arr 数组 */ sum: (arr) => { return arr.reduce((pre, cur) => { return pre + cur }) }, /**@average * 数组中 平均值 * arr 数组 */ average: (arr) => { return this.sum(arr) / arr.length }, /**@isObjectEqual * 数判断两个对象是否键值相同 * a, b 对象 */ isObjectEqual: (a, b) => { var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b); if (aProps.length !== bProps.length) { return false; } for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; if (a[propName] !== b[propName]) { return false; } } return true; }, /**@throttle * 节流函数--规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。 * fun 监控的函数 * delay 触发时间 */ throttle: (fun, delay) => { let last, deferTimer return function(args) { let that = this let _args = args let now = +new Date() if (last && now < last + delay) { clearTimeout(deferTimer) deferTimer = setTimeout(function() { last = now fun.apply(that, _args) }, delay) } else { last = now fun.apply(that, _args) } } }, /**@debouncer * 防抖 * fn 方法 * w 间隔时间 * im true 直接触发,false定时触发 */ debouncer: (fn, w, im) => { var T; return function() { var t = this; let a = arguments; if (T) clearTimeout(T); if (im) { // 如果已经执行过,不再执行 var cN = !T; T = setTimeout(function() { T = null; }, w) if (cN) fn.apply(t, a) } else { T = setTimeout(function() { fn.apply(t, a) }, w); } } }, /**@ArrayObjSort * 数组对象排序 * ArrayObj 数组对象 * key 对象中的key * sequence 排序方法 'a-b','b-a' */ ArrayObjSort: (ArrayObj, key, sequence) => { function sortkey(a, b) { switch (sequence) { case 'a-b': return a[key] - b[key]; case 'b-a': return b[key] - a[key]; } } ArrayObj.sort(sortkey); return ArrayObj; }, /**@randomString * 获取唯一值 * */ uniqueStr: () => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }, /**@randomString * 获取随机值 * e 随机值的长度 */ randomStr: (e) => { // let dateStr = Date.now();//13 e = e || 32; var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789", a = t.length, n = ""; for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a)); return n //+dateStr } } //验证规则 const regExp = { //手机 phone: (s) => { return /^(1[3-9])\d{9}$/.test(s) }, //邮箱 isEmail: (s) => { return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s) }, //手机号码 isMobile: (s) => { return /^1[0-9]{10}$/.test(s) }, //电话号码 isPhone: (s) => { return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s) }, //是否url地址 isURL: (s) => { return /^http[s]?:\/\/.*/.test(s) }, // 首字母大写 isCapital: (s) => { return /\b[^\Wa-z][^\WA-Z]*\b/g.test(s); }, //是否字符串 isString: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'String' }, //是否数字 isNumber: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Number' }, //是否boolean isBoolean: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean' }, //是否函数 isFunction: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Function' }, //是否为null isNull: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Null' }, //是否undefined isUndefined: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined' }, //是否对象 isObj: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Object' }, //是否数组 isArray: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Array' }, //是否时间 isDate: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Date' }, //是否正则 isRegExp: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp' }, //是否错误对象 isError: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Error' }, //是否Symbol函数 isSymbol: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol' }, //是否Promise对象 isPromise: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Promise' }, //是否Set对象 isSet: (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Set' }, //是否是微信浏览器 isWeiXin: () => { var ua = window.navigator.userAgent.toLowerCase(); return ua.match(/microMessenger/i) == 'micromessenger' }, //是否是移动端 isDeviceMobile: () => { var ua = window.navigator.userAgent.toLowerCase(); return /android|webos|iphone|ipod|balckberry/i.test(ua) }, //是否是QQ浏览器 isQQBrowser: () => { var ua = window.navigator.userAgent.toLowerCase(); return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i) }, //是否ios 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端 isPC: () => { var userAgentInfo = window.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; }, // 严格的身份证校验 isCardID: (sId) => { if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) { console.log('你输入的身份证长度或格式错误') return false } //身份证城市 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))]) { console.log('你的身份证地区非法') return false } // 出生日期验证 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())) { console.log('身份证上的出生日期非法') return false } // 身份证号码校验 var sum = 0, weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], codes = "10X98765432" for (var i = 0; i < sId.length - 1; i++) { sum += sId[i] * weights[i]; } var last = codes[sum % 11]; //计算出来的最后一位身份证号码 // console.log(last) if (sId[sId.length - 1] != last) { console.log('你输入的身份证号非法') return false } return true } } // 获取IP const ipurl = 'https://pv.sohu.com/cityjson?ie=utf-8'; const _try_ = (callback) => { try { callback() } catch (error) { // console.log(1); // uni ? uni.hideLoading() : alert('未知错误'); } }; export{ md, // regExp, //验证规则 ipurl, //ip _try_ } // 移动端适配方案 (function(doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function() { var clientWidth = docEl.clientWidth; var fontSize = 20; docEl.style.fontSize = fontSize + 'px'; var docStyles = getComputedStyle(docEl); var realFontSize = parseFloat(docStyles.fontSize); var scale = realFontSize / fontSize; console.log("realFontSize: " + realFontSize + ", scale: " + scale); fontSize = clientWidth / 667 * 20; if (isIphoneX()) fontSize = 19; fontSize = fontSize / scale; docEl.style.fontSize = fontSize + 'px'; }; // Abort if browser does not support addEventListener if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); // iphoneX判断 function isIphoneX() { return /iphone/gi.test(navigator.userAgent) && (win.screen.height == 812 && win.screen.width == 375) } })(document, window); // (!function (d) { // var c = d.document; // var a = c.documentElement; // var b = d.devicePixelRatio; // var f; // function e() { // var h = a.getBoundingClientRect().width, g; // if (b === 1) { // h = 720 // } // if (h > 720) h = 720;//设置基准值的极限值 // g = h / 7.2; // a.style.fontSize = g + "px" // } // if (b > 2) { // b = 3 // } else { // if (b > 1) { // b = 2 // } else { // b = 1 // } // } // a.setAttribute("data-dpr", b); // d.addEventListener("resize", function () { // clearTimeout(f); // f = setTimeout(e, 200) // }, false); // e() // })(window);