前端 常用工具总结
js:
//string skill //1.格式换金钱 const ThousandNum = num => num.tostring().replace(/\B(?=(\d{3})+(?!\d))/g, ",") //2.生成随机ID const RandomID = len => Math.random().toString(36).substr(3, len) //3.生成随机HEX色值 const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0") //4.生成星级pingfe const StarScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate) //number skill //1.取整 代替正数的Math.floor(),代替负数的Math.ceil() const number = ~~1.69; const number2 = 1.69 | 0; const number3 = 1.69 >> 0; // 都是1 //2.补零 const FillZero = (num,len) => num.toString().padStart(len, '0') //3.判断奇偶 const OddEven = (num) => !!(num & 1) ? 'odd' : 'even' //4.生成范围内随机数 const RandomNumber = (min,max) => Math.floor(Math.random()*(max - min + 1)) + min; //boolean skill //1.短路 // const a = d && 1; // 满足条件赋值:取假运算,从左到右依次判断,遇到假值返回假值,后面不再执行,否则返回最后一个真值 // const b = d || 1; // 默认赋值:取真运算,从左到右依次判断,遇到真值返回真值,后面不再执行,否则返回最后一个假值 // const c = !d; // 取假赋值:单个表达式转换为true则返回false,否则返回true //2.类型判断 const DataType = (data,type) => { let dataType = Object.prototype.toString.call(data).replace(/\[object (\w+)\]/, "$1").toLowerCase(); return type ? dataType === type : dataType } const all = (arr,fn) => { return arr.every(fn) } const arrayToCSV = (arr, delimiter = ',') => { return arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n') } //去除数组无效值 const compact = (arr) => arr.filter(Boolean) //递归扁平化数组 const deepPlatten = arr => [].concat(...arr.map( v => (Array.isArray(v))?deepPlatten(v):v)) //根据id生成树 const nest = (arr, id, pid) => { return arr.filter( item => item[pid] === id).map(el => ({...el,children: nest(arr, el.id)})) } //捕获异常 const attempt = (fn, ...args) => { try{ return fn(...args) }catch(e){ return e instanceof Error ? e : new Error(e) } } const equals = (a, b) => { if (a === b) return true; if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; if (a.prototype !== b.prototype) return false; let keys = Object.keys(a); if (keys.length !== Object.keys(b).length) return false; return keys.every(k => equals(a[k], b[k])); }; //获取url参数 const getQueryString = (name) => { const reg = new RegExp('^|&' + name + '=([^&]*)(&|$)','i'); const search = window.location.search.split('?')[1] || ''; const r = search.match(reg) || []; return r[2] } //根据url下载 const download = (url) => { let isChrome = navigator.userAgent.toLowerCase().indexOf('chromw') > -1; let isSafri = navigator.userAgent.toLowerCase().indexOf('safri') > -1; if(isChrome || isSafri) { const link = document.createElement('a'); link.href = url; if(link.download !== undefined){ let fileName = url.subString(url.lastIndexOf('/') + 1, url.length); link.download = fileName; } if(document.createEvent){ let e = document.createEvent('MounseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true } } if(url.indexOf('?') === -1){ url += '?download'; } window.open(url, '_self'); return true; } //滚动到顶部 const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if(c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c-c/8) } } //检查el是否在视图范围内 const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, right, bottom, left } = 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; } //洗牌随机算法 const shuffle = (arr) => { let result = [], random; while(arr.length > 0) { random = Math.floor(Math.random() * arr.length); result.push(arr[random]); arr.splice(random, 1) } return result } //随机数范围 Math.random() => [0,1) const randomNumer = (min, max) => { return Math.floor(min + Math.random() * ((max + 1) - min)) } //去除空格 type: 1-所有空格 2-前后空格 3-前空格 4-后空格 const trim = (str, type) => { type = type || 1 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; } }
// 1.类型检测类 //字符串 function isString(o){ return Object.prototype.toString.call(o).slice(8,-1) === 'String' } //数字 function isNumber(o){ return Object.prototype.toString.call(o).slice(8,-1) === 'Number' } //对象 function isObject(o){ return Object.prototype.toString.call(o).slice(8,-1) === 'Object' } //数组 function isArray(o){ return Object.prototype.toString.call(o),sllice(8,-1) === 'Array' } //手机类型 function mobileType(){ let u = navigator.userAgent; if(u.indexOf('Android') > -1 || u.indexOf('Linux' > -1)){ return 'Android' } else if(u.indexOf('iPhone') > -1){ return 'iPhone' } else if(u.indexOf('iPad') > -1){ return 'iPad' } } //字符串检测 function strCheck(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})?$/.test(str); case 'card'://身份证 return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str); case 'pwd': return /^[a-zA-z]\w{5,17}$/.test(str); case 'email': return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case 'number': return /^[0-9]{6}$/.test(str) } } //日期类 //格式化 function timeFormat(obj){ let temDate = obj.date || new Date(),format = obj.format || "-"; // let y = temDate.getFullYear(), // m = temDate.getMonth() + 1 > 9 ? temDate.getMonth() + 1 : '0' + temDate.getMonth() + 1, // d = temDate.getDate() > 9 ? temDate.getDate() : '0' + temDate.getDate(), // h = temDate.getHours() > 9 ? temDate.getHours() : '0' + temDate.getHours(), // mi = temDate.getMinutes > 0 ? temDate.getMinutes : '0' + temDate.getMinutes, // s = temDate.getSeconds() > 9 ? temDate.getSeconds() : '0' + temDate.getSeconds(); let y = temDate.getFullYear(), m = compareNine(temDate.getMonth() + 1), d = compareNine(temDate.getDate()), h = compareNine(temDate.getHours()), mi = compareNine(temDate.getMinutes()), s = compareNine(temDate.getSeconds()); return y + format + m + format + d + " " + h + ":" + mi + ":" + s } function compareNine(val){ return val > 9 ? val : '0' + val } //日期比较大小 function timeCompare(one,two){ let oneDate = new Date(Date.parse(one)); let twoDate = new Date(Date.parse(two)); return oneDate<twoDate } //一周以前 function beforeWeekDate(date,format){ let temDate = date || new Date(); if(!(temDate instanceof Date)){ temDate = new Date(temDate.replace(/-/g, '/')); } let temDateTime = temDate.getTime(), weekDate = new Date(temDateTime - 7*24*60*60*1000); return timeFormat(weekDate,format) } //数组类 //判断一个元素是否在数组内 function contains(str,arr){ return arr.indexOf(str) > -1 } //封装map function myMap(arr,fn,thisObj){ let scope = thisObj || window, returnArray = []; for(let i=0,j=arr.length;i<j;i++){ let res = fn.call(scope,arr[i],i,this); if(res != null){ returnArray.push(res) } } return returnArray; } //封装 each function myEach(arr,fn){ let returnArray = [],_fn = fn || Function; let args = Array.prototype.slice.call(arguments,1); for(let i=0,j=arr.length;i<j;i++){ let res = fn.apply(arr,[arr[i],i].concat(args)) if(res != null){ returnArray.push(res) } } } //排序 1 升序 2 降序 3 随机 4 自己 function mySort(arr,type){ let arrLen = arr.length; if(arrLen === 0 || arrLen === 1){ return arr; } return arr.sort(function(a,b){ switch(type){ case 1: return a - b; case 2: return b - a; case 3: return Math.random() - 0.5; default: return arr } }) } //去重 function myUinique(arr){ if(Array.hasOwnProperty('from')){ return Array.from(new Set(arr)) } else{ let a = [],o = {}; for(let i=0,j=arr.length;i<j;i++){ if(!o[arr[i]]){ o[arr[i]] = true; a.push(arr[i]) } } return a } } //最大值 function myMax(arr){ return Math.max.apply(null,arr) } //最小值 function myMin(arr){ return Math.min.apply(null,arr) } //类数组 -> 数组 function arrLikeToArr(arrLike){ let arr = []; if(Array.isArray(arrLike)){ arr = arrLike } else{ arr = Array.prototype.slice.call(arrLike) } return arr; } //string类 //去空格 1 所有 2 前后 3 前 4 后 function myTrim(str,tp){ let type = tp || 1; 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,'') } } //大小写变化 1:首字母大写 2:首页母小写 3:大小写转换 4:全部大写 5:全部小写 function changeCase(str,tp){ let type = tp || 1; switch(type){ case 1: return str.replace(/\b\w+\b/g,function(word){ return word.substring(0,1).toUpperCase() + word.substring(1).toLowerCase() }) case 2: return str.replace(/\b\w+\b/g/g,function(word){ return word.substring(0,1).toLowerCase() + word.substring(1).toUpperCase() }) case 3: return str.split('').map(function(word){ if(/[a-z]/.test(word)){ return word.toUpperCase() } else{ return word.toLowerCase() } }).join(''); case 4: return str.toUpperCase(); case 5: return str.toLowerCase(); } } //密码强度 function pwdCheck(str){ let LV = 0; if(str.length < 6){ return Lv; } if(/[0,9]/.test(str)){ return LV++ } if(/[a-z]/.test(str)){ return LV++ } if(/[A-Z]/.test(str)){ return LV++ } if(/[\.|-|_]/.test(str)){ return LV++ } return LV++ } //number类 //随机数 function randomNumber(min,max){ if(arguments.length === 2){ return Math.floor(min + Math.random() * (max + 1 - min)) } else{ return null } } //补零 position:1 前 2 后 _length 返回的数据长度 function addZero(param,_length,position){ let len = param + "", dataArr = len.split(""), lenHandle = dataArr.length, num = _length - lenHandle; if(num<0){ return param; } for (let i = 0; i < num; i++) { if(position === 1){ dataArr.unshift("0") } else if(position === 2){ dataArr.push("0") } } let nowData = dataArr.join(""); return nowData; } //存储类 function setSession(name,val){ return sessionStorage.setItem(name,val) } function getSession(name){ return sessionStorage.getItem(name) } function setCookie(name,val,time){ let setting = arguments[0]; if(Object.prototype.toString.call(setting).slice(8,-1) === 'Object'){ for(let i in setting){ let oDate = new Date(); oDate.setDate(oDate.getDate() + time); document.cookie = name + '=' + val + ';expires=' + oDate; } } else{ let oDate = new Date(); oDate.setDate(oDate.getDate() + time); document.cookie = name + '=' + val + ';expires=' + oDate; } } function getCookie(name){ let arr = document.cookie.split(';'); for(let i=0,j=arr.length;i<j;i++){ let arr2 = arr[i].split('='); if(arr2[0] === name ){ return arr2[1] } } } //防抖 //节流 //监听input框 //倒计时 //事件绑定,监听,解绑 //事件冒泡 阻止冒泡 阻止默认行为
css *{ padding:0; margin:0 } html,body{ -webkit-text-size-adjust: 100%; width: 100%; height: 100%; font-family: "微软雅黑" } acticle,aside,footer,header,nav,section{ display: block } ul,li{ list-style: none; } a{ text-decoration: none } button, input, optgroup, select, textarea { font-family: sans-serif; /* 1 */ font-size: 100%; /* 1 */ line-height: 1.15; /* 1 */ margin: 0; /* 2 */ } /* 禁止文本选中 */ .usn{ -webkit-user-select:none; -moz-user-select:none; -ms-user-select:none; -o-user-select:none; user-select:none; } textarea { overflow: auto; } .box-sizing-border{ box-sizing: border-box } .box-sizing-content{ box-sizing: content-box } .display-block{ display: block } .display-inline{ display: inline; } .display-inline-block{ display:inline-block } .display-flex{ display:flex; } .shadow-5-111{ box-shadow:0 0 5px #111; } .shadow-10-111{ box-shadow:0 0 10px #111; } .shadow-5-eee{ box-shadow:0 0 5px #eee; } .shadow-10-eee{ box-shadow:0 0 10px #eee; } /* 内容居中 */ .content-center{ display:flex; justify-content: center; align-items:center } /* 三角形 一边颜色 其余三边 transparent*/ .triangle{ width:0; height:0; border-style:solid; border-width: 20px; border-color: red yellow green lightblue } .fz-12{ font-size: 12px; } .fz-14{ font-size: 14px; } .fz-16{ font-size: 16px; } .color-red{ color:red; } .color-green{ color:green; } .color-white{ color:white; } .color-black{ color:black } .color-blue{ color:blue } .color-gray{ color:gray; } .bg-eee{ background:#eee; } .bg-111{ background:#111; } .bg-fff{ background: #fff; } .margin-10{ margin:10px } .margin-20{ margin:20px } .margin-30{ margin:30px; } .margin-40{ margin:40px; } .padding-10{ padding:10px } .padding-20{ padding:20px } .padding-30{ padding:30px; } .padding-40{ padding:40px; } .input-36{ width:100%; height:38px } .input-20{ width:100%; height:20px } .div-20{ height: calc( 100vh - 20px); } .div-40{ height: calc( 100vh - 40px); } .div-100{ height: calc( 100vh - 100px); } .div-200{ height: calc( 100vh - 200px); } /* 定位 */ .position-fixed{ position:fixed } .position-absolute{ position:absolute } .position-relative{ position: relative; } /* 浮动 */ .fl{ float: left; } .fr{ float:right; } /* 清除浮动 */ .clear-fix:after { content:""; display:block; height:0; clear:both; visibility:hidden; } /* input 为number 隐藏 后面的图标 */ input[type=number] { -moz-appearance:textfield; } input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; } /* placeholder */ input::-webkit-input-placeholder{ color:#c0c3cc; } input::-moz-placeholder{ color:#c0c3cc; } input:-ms-input-placeholder{ color:#c0c3cc; } /* input 为pwd ie去除图标 */ ::-ms-clear,::-ms-reveal{display:none;} /* loading层 */ .cover{ position:fixed; height: 100%; width:100%; top:0; left:0; display: flex; justify-content: center; align-items: center; } /* 换行 */ /* 不换行 */ .word-none{ word-wrap: normal; word-wrap: nowrap; } /* 换行 */ .word-break{ white-space: normal; word-wrap: break-word; word-break: break-all } /* 多余超出省略号 宽度自定义*/ .wote{ max-width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* 鼠标样式 */ .cursor-pointer{ cursor:pointer } .cursor-help{ cursor:help } .cursor-default{ cursor:default } .cursor-move{ cursor:move } /*默认滚动条样式修改ie9 google Firefox 等高版本浏览器有效*/ /*::selection {background: #D03333;color: white;text-shadow: none;} ::-webkit-scrollbar-track-piece{width:10px;font-style: italic;">::-webkit-scrollbar{width:10px;height:6px} ::-webkit-scrollbar-thumb{height:50px;} ::-webkit-scrollbar-thumb:hover{background:#cc0000}*/