Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Share tutorials on encapsulation of JavaScript and CSS common tools and methods

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "sharing the package tutorial of common tools and methods of JavaScript and CSS". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

JavaScript

Type type judgment

IsString (o) {/ / whether the string return Object.prototype.toString.call (o) .slice (8,-1) = = 'String'} isNumber (o) {/ / whether it is numeric return Object.prototype.toString.call (o) .slice (8,-1) = =' Number'} isBoolean (o) {/ / whether boolean return Object.prototype.toString.call (o) .slice (8) -1) = = 'Boolean'} isFunction (o) {/ / whether function return Object.prototype.toString.call (o) .slice (8,-1) = =' Function'} isNull (o) {/ / whether it is null return Object.prototype.toString.call (o) .slice (8,-1) = = 'Null'} isUndefined (o) {/ / whether undefined return Object.prototype.toString.call (o) .slice (8) -1) = = 'Undefined'} isObj (o) {/ / whether object return Object.prototype.toString.call (o) .slice (8,-1) = =' Object'} isArray (o) {/ / whether array return Object.prototype.toString.call (o) .slice (8,-1) = = 'Array'} isDate (o) {/ / whether time return Object.prototype.toString.call (o) .slice (8) -1) = = 'Date'} isRegExp (o) {/ / whether regular return Object.prototype.toString.call (o) .slice (8,-1) = =' RegExp'} isError (o) {/ / wrong object return Object.prototype.toString.call (o) .slice (8,-1) = = 'Error'} isSymbol (o) {/ / whether Symbol function return Object.prototype.toString.call (o) .slice (8) -1) = = 'Symbol'} isPromise (o) {/ / whether Promise object return Object.prototype.toString.call (o) .slice (8,-1) = =' Promise'} isSet (o) {/ / whether Set object return Object.prototype.toString.call (o) .slice (8) -1) = = 'Set'} isFalse (o) {if (! o | | o =' null' | | o = 'undefined' | | o =' false' | | o = 'NaN') return true return false} isTrue (o) {return! this.isFalse (o)} isIos () {var u = navigator.userAgent If (u.indexOf ('Android') >-1 | | u.indexOf (' Linux') >-1) {/ / Android phone / / return "Android"; return false} else if (u.indexOf ('iPhone') >-1) {/ / iPhone / / return "iPhone"; return true} else if (u.indexOf (' iPad') >-1) {/ / iPad / / return "iPad" Return false} else if (u.indexOf ('Windows Phone') >-1) {/ / winphone phone / / return "Windows Phone"; return false} else {return false}} isPC () {/ / whether it is PC 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;} browserType () {var userAgent = navigator.userAgent; / / get the browser's userAgent string var isOpera = userAgent.indexOf ("Opera") >-1; / / determine whether the Opera browser var isIE = userAgent.indexOf ("compatible") >-1 & & userAgent.indexOf ("MSIE") >-1 & &! isOpera / / determine whether the IE browser var isIE11 = userAgent.indexOf ('Trident') >-1 & & userAgent.indexOf ("rv:11.0") >-1; var isEdge = userAgent.indexOf ("Edge") >-1 & &! isIE; / / determine whether the Edge browser of IE var isFF = userAgent.indexOf ("Firefox") >-1 / / determine whether the Firefox browser var isSafari = userAgent.indexOf ("Safari") >-1 & & userAgent.indexOf ("Chrome") = =-1; / / determine whether the Safari browser var isChrome = userAgent.indexOf ("Chrome") >-1 & userAgent.indexOf ("Safari") >-1; / / determine whether the Chrome browser if (isIE) {var reIE = new RegExp ("MSIE (\\ d+\\.\\ d+);") ReIE.test (userAgent); var fIEVersion = parseFloat (RegExp ["$1"]); if (fIEVersion = = 7) return "IE7" else if (fIEVersion = = 8) return "IE8"; else if (fIEVersion = = 9) return "IE9"; else if (fIEVersion = = 10) return "IE10"; else return "IE7 below" / / IE version is too low} 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': / / Mobile number return / ^ 1 [3 | 4 | 5 | 7 | 8 | 9] [0-9] {9} $/ .test (str) Case 'tel': / / landline return / ^ (0\ d {2Magne3} -\ d {7score8}) (-\ d {1score4})? $/ .test (str); case' card': / / ID card return / (^\ d {15} $) | (^\ d {18} $) | (^\ d {17} (\ d | X | x) $) / .test (str) The case 'pwd': / / password begins with a letter and is between 6 and 18 in length. It can only contain letters, numbers, and underscores return / ^ [a-zA-Z]\ w {5pm 17} $/ .test (str) case' postal': / / zip code return / [1-9]\ d {5} (?!\ d) / .test (str) Case 'QQ': / / QQ return / ^ [1-9] [0-9] {4 email': 9} $/ .test (str); case' email': / / email return / ^ [\ w -] + (\ .[\ w -] +) * @ [\ w -] + (\ .[\ w -] +) + $/ .test (str) Case 'money': / / amount (2 decimal places) return / ^\ d * (?:\.\ d {0jue 2})? $/ .test (str) Case 'URL': / / URL return / (http | ftp | https):\ /\ / [\ w\-_] + (\ .[\ w\-_] +) + ([\ w\ -\. @? ^ =% &: / ~\ + #] * [\ w\ -\ @? ^ =% & / ~\ + #])? / .test (str) 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) / .test (str) Case 'date': / / date time return / ^ (\ d {4})\-(\ d {2})\-(\ d {2}) (\ d {2}) (\ d {2}) (?:\ d {2} |: (\ d {2}): (\ d {2})) $/ .test (str) | / ^ (\ d {4})\-(\ d {2})\-(\ d {2}) }) $/ .test (str) case 'number': / / Digital return / ^ [0-9] $/ .test (str) Case 'english': / / English return / ^ [a-zA-Z] + $/ .test (str); case' chinese': / / Chinese return / ^ [\ u4E00 -\ u9FA5] + $/ .test (str); case 'lower': / / lowercase return / ^ [Amurz] + $/ .test (str) Case 'upper': / / uppercase return / ^ [Amurz] + $/ .test (str); case' HTML': / / HTML tag return /]) * > / .test (str); default: return true } / / strict ID card verification isCardID (sId) {if (! / (^\ d {15} $) | (^\ d {17} (\ d | X | x) $) / .test (sId) {alert ('incorrect ID card length or format') return false} / / ID card city var aCity= {11: "Beijing" 12: "Tianjin", 13: "Hebei", 14: "Shanxi", 15: "Inner Mongolia", 21: "Liaoning", 22: "Jilin", 23: "Heilongjiang", 31: "Shanghai", 32: "Jiangsu", 33: "Zhejiang", 34: "Anhui", 35: "Fujian", 36: "Jiangxi", 37: "Shandong", 41: "Henan", 42: "Hubei", 43: "Hunan", 44: "Guangdong" 45: Guangxi, 46: Hainan, 50: Chongqing, 51: Sichuan, 52: Guizhou, 53: Yunnan, 54: Xizang, 61: Shaanxi, 62: Gansu, 63: Qinghai, 64: Ningxia, 65: Xinjiang, 71: Taiwan, 81: Hong Kong, 82: Macao, 91: abroad} If (! aCity [parseInt (sId.substr (0Magne2)]) {alert ('your ID card area is illegal') return false} / / date of birth verification var sBirthday= (sId.substr (6Power4) + "-" + Number (sId.substr (10Power2)) + "-" + Number (sId.substr (12j2) .replace (/-/ g, "/") D = new Date (sBirthday) if (sBirthday! = (d.getFullYear () + "+ (d.getMonth () + 1) +" / "+ d.getDate ()) {alert ('illegal date of birth on ID card') return false} / / ID card number check 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]; //计算出来的最后一位身份证号码 if (sId[sId.length-1] != last) { alert('你输入的身份证号非法') return false } return true }}前端技术分享:[q群---784783012](http://u6.gg/eUpjy) 2. Date /** * 格式化时间 * * @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) return null if ((time +'). Length = = 10) {time = + time * 1000} var format = cFormat | |'{y}-{m}-{d} {h}: {I}: {s}' Date if (typeof time = 'object') {date = time} else {date = new Date (time)} var formatObj = {y: date.getFullYear (), m: date.getMonth () + 1, d: date.getDate (), h: date.getHours (), I: date.getMinutes (), s: date.getSeconds () A: date.getDay ()} var time_str = format.replace (/ {(y | m | d | I | s | a) +} / g, (result, key) = > {var value = formatObj [key] if (key ='a') return ['one', 'two', 'three', 'four', 'five', 'six', 'day'] [value-1] if (result.length > 0 & value)

< 10) { value = '0' + value } return value || 0 }) return time_str}/** * 返回指定长度的月份集合 * * @param {time} 时间 * @param {len} 长度 * @param {direction} 方向: 1: 前几个月; 2: 后几个月; 3:前后几个月 默认 3 * @return {Array} 数组 * * @example getMonths('2018-1-29', 6, 1) // ->

["2018-1", "2017-12", "2017-11", "2017-10", "2017-9", "2017-8", "2017-7"] * / getMonths (time, len, direction) {var mm = new Date (time). GetMonth (), yy = new Date (time). GetFullYear (), direction = isNaN (direction)? 3: direction, index = mm Var cutMonth = function (index) {if (index =-len) {return direction = = 1? FormatPre (index). Concat (cutMonth (+ + index)): direction = = 2? FormatNext (index) .concat (cutMonth (+ + index)): formatCurr (index) .concat (cutMonth (+ + index))} return []} var formatNext = function (I) {var y = Math.floor (iCompa 12), m = I return [yy+y +'-'+ (massif 1)]} var formatPre = function (I) {var y = Math.ceil (iLever 12) M = I m = m return 0? 12: M return [yy-y +'-'+ (13-m)]} var formatCurr = function (I) {var y = Math.floor (I mNext 12), yNext = Math.ceil (I mNext 12), m = I, mNext = m return [yy-yNext +'-'+ (13-mNext) Yy+y +'-'+ (new Set 1)]} / / Array deduplication var unique = function (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; } } return direction !== 3 ? cutMonth(index) : unique(cutMonth(index).sort(function(t1, t2){ return new Date(t1).getTime() - new 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, len Diretion) {var tt = new Date (time) var getDay = function (day) {var t = new Date (time) t.setDate (t.getDate () + day) var m = t.getMonth () + 1 return t.getFullYear () +'-'+ m+'-'+t.getDate ()} var arr = [] if (diretion = 1) {for (var I = 1) I {switch (type) {case 1: return a-b; case 2: return b-a; case 3: return Math.random ()-0.5; default: return arr })} / * deduplicated * / 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; } // 注:上面 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); return this.unique(newArr);}/*求两个集合的交集*/intersect (a, b) { var _this = this; a = this.unique(a); return this.map(a, function(o) { return _this.contains(b, o) ? o : null; });}/*删除其中一个元素*/remove (arr, ele) { var index = arr.indexOf(ele); if(index >

-1) {arr.splice (index, 1);} return arr;} / * method for converting a class array to an array * / formArray (ary) {var arr = []; if (Array.isArray (ary)) {arr = ary;} else {arr = Array.prototype.slice.call (ary);}; return arr } / * maximum * / max (arr) {return Math.max.apply (null, arr);} / * minimum * / min (arr) {return Math.min.apply (null, arr);} / * summation * / sum (arr) {return arr.reduce ((pre, cur) = > {return pre + cur})} / * average * / average (arr) {return this.sum (arr) / arr.length}

4. String string operation

/ * * remove spaces * @ param {str} * @ param {type} * type: 1-all spaces 2-before and after spaces 3-leading spaces 4-trailing spaces * @ return {String} * / trim (str, type) {type = type | 1 switch (type) {case 1: return str.replace (/\ sblank Unipletg, "") 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 }} / * * @ param {str} * @ param {type} * type: 1: first letter uppercase 2: home mother lowercase 3: uppercase conversion 4: all uppercase 5: all lowercase * @ return {String} * / changeCase (str, type) {type = type | | 4 switch (type) {case 1: return str.replace (/\ b\ w+\ bbank g) Function (word) {return word.substring (0,1) .toUpperCase () + word.substring (1) .toLowerCase () }); case 2: return str.replace (/\ b\ w +\ b return word.substring g, function (word) {return word.substring (0,1). ToLowerCase () + word.substring (1). ToUpperCase ();}) Case 3: return str.split ('') .map (function (word) {if (/ [Amurz] / .test (word)) {return word.toUpperCase () } else {return word.toLowerCase ()}) .join ('') case 4: return str.toUpperCase (); case 5: return str.toLowerCase (); default: return str }} / * detect password strength * / checkPwd (str) {var Lv = 0; if (str.length)

< 6) { return Lv } if (/[0-9]/.test(str)) { Lv++ } if (/[a-z]/.test(str)) { Lv++ } if (/[A-Z]/.test(str)) { Lv++ } if (/[\.|-|_]/.test(str)) { Lv++ } return Lv;}/*过滤html代码(把转换)*/filterTag (str) { str = str.replace(/&/ig, "&"); str = str.replace(//ig, ">

"); str = str.replace (", "); return str;}

5. Number

/ * Random number range * / random (min, max) {if (arguments.length = 2) {return Math.floor (min + Math.random () * ((max+1)-min))} else {return null Translation of Arabic numerals into Chinese capitals * / numberToChinese (num) {var AA = new Array (zero, one, two, three, four, five, six, seven, eight, nine, ten) Var BB = new Array ("", "ten", "hundred", "thousand", "ten thousand", "ten million", "point", ""); var a = ("" + num). Replace (/ (^ 0*) / g, "). Split (". "), k = 0, re ="; for (var I = a [0] .length-1; I > = 0 Re -) {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; kryptonite;} if (a.length > 1) / / plus fractional part (if there is a fractional part) {re + = BB [6]; for (charat 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;}/*将数字转换为大写金额*/changeToChinese (Num) { //判断如果传递进来的不是字符的话转换为字符 if(typeof Num == "number") { Num = new String(Num); }; Num = Num.replace(/,/g, "") //替换tomoney()中的"," Num = Num.replace(/ /g, "") //替换tomoney()中的空格 Num = Num.replace(/¥/g, "") //替换掉可能出现的¥字符 if(isNaN(Num)) { //验证输入的字符是否为数字 //alert("请检查小写金额是否正确"); return ""; }; //字符处理完毕后开始转换,采用前后两部分分别转换 var part = String(Num).split("."); var newchar = ""; //小数点前进行转化 for(var i = part[0].length - 1; i >

= 0; iMel -) {if (part [0] .length > 10) {return "; / / if the quantity exceeds one billion units, prompt} var tmpnewchar ="var perchar = part [0] .charat (I) Switch (perchar) {case "0": tmpnewchar = "zero" + tmpnewchar; break; case "1": tmpnewchar = "one" + tmpnewchar; break; case "2": tmpnewchar = "II" + tmpnewchar Break; case "3": tmpnewchar = "3" + tmpnewchar; break; case "4": tmpnewchar = "restaurant" + tmpnewchar; break; case "5": tmpnewchar = "Wu" + tmpnewchar Break; case "6": tmpnewchar = "Lu" + tmpnewchar; break; case "7": tmpnewchar = "7" + tmpnewchar; break; case "8": tmpnewchar = "Lu" + tmpnewchar Break; case "9": tmpnewchar = "Jiu" + tmpnewchar; break;} switch (part [0] .length-I-1) {case 0: tmpnewchar = tmpnewchar + "Yuan"; break Case 1: if (perchar! = 0) tmpnewchar = tmpnewchar + "pick up"; break; case 2: if (perchar! = 0) tmpnewchar = tmpnewchar + "hundred"; break; case 3: if (perchar! = 0) tmpnewchar = tmpnewchar + "thousand" Break; case 4: tmpnewchar = tmpnewchar + "ten thousand"; break; case 5: if (perchar! = 0) tmpnewchar = tmpnewchar + "pick"; break Case 6: if (perchar! = 0) tmpnewchar = tmpnewchar + "hundred"; break; case 7: if (perchar! = 0) tmpnewchar = tmpnewchar + "thousand"; break; case 8: tmpnewchar = tmpnewchar + "100 million" Break; case 9: tmpnewchar = tmpnewchar + "pick"; break;} var newchar = tmpnewchar + newchar } / / convert if (Num.indexOf (".")! =-1) {if (part [1] .length > 2) {/ / alert ("only two digits can be retained after the decimal point, the system will be truncated automatically") Part [1] = part [1] .substr (0,2)} for (I = 0; I

< part[1].length; i++) { tmpnewchar = "" perchar = part[1].charAt(i) switch(perchar) { case "0": tmpnewchar = "零" + tmpnewchar; break; case "1": tmpnewchar = "壹" + tmpnewchar; break; case "2": tmpnewchar = "贰" + tmpnewchar; break; case "3": tmpnewchar = "叁" + tmpnewchar; break; case "4": tmpnewchar = "肆" + tmpnewchar; break; case "5": tmpnewchar = "伍" + tmpnewchar; break; case "6": tmpnewchar = "陆" + tmpnewchar; break; case "7": tmpnewchar = "柒" + tmpnewchar; break; case "8": tmpnewchar = "捌" + tmpnewchar; break; case "9": tmpnewchar = "玖" + tmpnewchar; break; } 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("亿万", "亿"); newchar = newchar.replace("零万", "万"); newchar = newchar.replace("零元", "元"); newchar = newchar.replace("零角", ""); newchar = newchar.replace("零分", ""); if(newchar.charAt(newchar.length - 1) == "元") { newchar = newchar + "整" } return newchar; } 6. Http /** * @param {setting} */ajax(setting){ //设置参数的初始值 var opts={ method: (setting.method || "GET").toUpperCase(), //请求方式 url: setting.url || "", // 请求地址 async: setting.async || true, // 是否异步 dataType: setting.dataType || "json", // 解析方式 data: setting.data || "", // 参数 success: setting.success || function(){}, // 请求成功回调 error: setting.error || function(){} // 请求失败回调 } // 参数格式化 function params_format (obj) { var str = '' for (var i in obj) { str += i + '=' + obj[i] + '&' } return str.split('').slice(0, -1).join('') } // 创建ajax对象 var xhr=new XMLHttpRequest(); // 连接服务器open(方法GET/POST,请求地址, 异步传输) if(opts.method == 'GET'){ xhr.open(opts.method, opts.url + "?" + params_format(opts.data), opts.async); xhr.send(); }else{ 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 = function() { if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) { switch(opts.dataType){ case "json": var json = JSON.parse(xhr.responseText); opts.success(json); break; case "xml": opts.success(xhr.responseXML); break; default: opts.success(xhr.responseText); break; } } } xhr.onerror = function(err) { opts.error(err); }}/** * @param {url} * @param {setting} * @return {Promise} */fetch(url, setting) { //设置参数的初始值 let opts={ method: (setting.method || 'GET').toUpperCase(), //请求方式 headers : setting.headers || {}, // 请求头设置 credentials : setting.credentials || true, // 设置cookie是否一起发送 body: setting.body || {}, mode : setting.mode || 'no-cors', // 可以设置 cors, no-cors, same-origin redirect : setting.redirect || 'follow', // follow, error, manual cache : setting.cache || 'default' // 设置 cache 模式 (default, reload, no-cache) } let dataType = setting.dataType || "json", // 解析方式 data = setting.data || "" // 参数 // 参数格式化 function params_format (obj) { var str = '' for (var i in obj) { str += `${i}=${obj[i]}&` } return str.split('').slice(0, -1).join('') } if (opts.method === 'GET') { url = url + (data?`?${params_format(data)}`:'') }else{ setting.body = data || {} } return 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)})}} frontend technology sharing: [Q group-784783012] (http://u6.gg/eUpjy)

7. DOM

(selector) {var type = selector.substring (0,1); if (type ='#') {if (document.querySelecotor) return document.querySelector (selector) return document.getElementById (selector.substring (1))} else if (type ='.') {if (document.querySelecotorAll) return document.querySelectorAll (selector) return document.getElementsByClassName (selector.substring (1))} else {return document ['querySelectorAll'? 'querySelectorAll':'getElementsByTagName'] (selector)}} / * Detection class name * / hasClass (ele, name) {return ele.className.match (new RegExp (' (\\ s | ^)'+ name +'(\\ s | $'));} / * add class name * / addClass (ele, name) {if (! this.hasClass (ele, name)) ele.className + = "" + name } / * Delete class name * / removeClass (ele, name) {if (this.hasClass (ele, name)) {var reg = new RegExp ('(\\ s | ^)'+ name +'(\\ s | $)'); ele.className = ele.className.replace (reg,');} / * replace class name * / replaceClass (ele, newName, oldName) {this.removeClass (ele, oldName); this.addClass (ele, newName) } / * get sibling node * / siblings (ele) {console.log (var [XSS _ clean]) var chid = Ele [XSS _ clean] .children, eleMatch = []; for (var I = 0, len = chid.length; I

< len; i ++){ if(chid[i] != ele){ eleMatch.push(chid[i]); } } return eleMatch;}/*获取行间样式属性*/getByStyle (obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; }else{ return getComputedStyle(obj,false)[name]; }} 8. Storage 储存操作 class StorageFn { constructor () { this.ls = window.localStorage; this.ss = window.sessionStorage; } /*-----------------cookie---------------------*/ /*设置cookie*/ setCookie (name, value, day) { var setting = arguments[0]; if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){ for (var i in setting) { var oDate = new Date(); oDate.setDate(oDate.getDate() + day); [xss_clean] = i + '=' + setting[i] + ';expires=' + oDate; } }else{ var oDate = new Date(); oDate.setDate(oDate.getDate() + day); [xss_clean] = name + '=' + value + ';expires=' + oDate; } } /*获取cookie*/ getCookie (name) { var arr = [xss_clean].split('; '); for (var i = 0; i < arr.length; i++) { var arr2 = arr[i].split('='); if (arr2[0] == name) { return arr2[1]; } } return ''; } /*删除cookie*/ removeCookie (name) { this.setCookie(name, 1, -1); } /*-----------------localStorage---------------------*/ /*设置localStorage*/ setLocal(key, val) { var setting = arguments[0]; if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){ for(var i in setting){ this.ls.setItem(i, JSON.stringify(setting[i])) } }else{ this.ls.setItem(key, JSON.stringify(val)) } } /*获取localStorage*/ getLocal(key) { if (key) return JSON.parse(this.ls.getItem(key)) return null; } /*移除localStorage*/ removeLocal(key) { this.ls.removeItem(key) } /*移除所有localStorage*/ clearLocal() { this.ls.clear() } /*-----------------sessionStorage---------------------*/ /*设置sessionStorage*/ setSession(key, val) { var setting = arguments[0]; if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){ for(var i in setting){ this.ss.setItem(i, JSON.stringify(setting[i])) } }else{ this.ss.setItem(key, JSON.stringify(val)) } } /*获取sessionStorage*/ getSession(key) { if (key) return JSON.parse(this.ss.getItem(key)) return null; } /*移除sessionStorage*/ removeSession(key) { this.ss.removeItem(key) } /*移除所有sessionStorage*/ clearSession() { this.ss.clear() }} 9. Other 其它操作 /*获取网址参数*/getURL(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = decodeURI_(window.location.search).substr(1).match(reg); if(r!=null) return r[2]; return null;}/*获取全部url参数,并转换成json对象*/getUrlAllParams (url) { var url = url ? url : _window.location.href; var _pa = url.substring(url.indexOf('?') + 1), _arrS = _pa.split('&'), _rs = {}; for (var i = 0, _len = _arrS.length; i < _len; i++) { var pos = _arrS[i].indexOf('='); if (pos == -1) { continue; } var name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1)); _rs[name] = value; } return _rs;}/*删除url指定参数,返回url*/delParamsUrl(url, name){ var baseUrl = url.split('?')[0] + '?'; var query = url.split('?')[1]; if (query.indexOf(name)>

-1) {var obj = {} var arr = query.split ("&"); for (var I = 0; I < arr.length; iTunes +) {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 (/\, / g," & "); return url} else {return url }} / * get hexadecimal random color * / getRandomColor () {return'#'+ (function (h) {return new Array (7-h.length) .join ("0") + h;}) ((Math.random () * 0x1000000 0) {dom.scrollTop = restoreTop;} dom.focus (); dom.selectionStart = startPos + val.length Dom.selectionEnd = startPos + val.length;} else {dom.value + = val; dom.focus ();}} frontend technology sharing: [Q group-784783012] (http://u6.gg/eUpjy)

CSS

Pc-reset PC style initialization

/ * normalize.css * / html {line-height: 1.15; / * 1 * /-ms-text-size-adjust: 100%; / * 2 * /-webkit-text-size-adjust: 100%; / * 2 * /} body {margin: 0;} article,aside,footer,header,nav,section {display: block;} H2 {font-size: 2em; margin: 0.67em 0;} figcaption,figure,main {/ * 1 * / display: block } figure {margin: 1em 40px;} hr {box-sizing: content-box; / * 1 * / height: 0; / * 1 * / overflow: visible; / * 2 * /} pre {font-family: monospace, monospace; / * 1 * / font-size: 1em; / * 2 * /} a {background-color: transparent; / * 1 * /-webkit-text-decoration-skip: objects; / * 2 * /} abbre [title] {border-bottom: none / * 1 * / text-decoration: underline; / * 2 * / text-decoration: underline dotted; / * 2 * /} b strong {font-weight: inherit;} b strong {font-weight: bolder;} code,kbd,samp {font-family: monospace, monospace; / * 1 * / font-size: 1em; / * 2 * /} dfn {font-style: italic;} mark {background-color: # ff0; color: # 000;} small {font-size: 80 } sub,sup {font-size: 75%; line-height: 0; position: relative; vertical-align: baseline;} sub {bottom:-0.25em;} sup {top:-0.5emm;} audio,video {display: inline-block;} audio:not ([controls]) {display: none; height: 0;} img {border-style: none;} svg:not (: root) {overflow: hidden } button,input,optgroup,select,textarea {font-family: sans-serif; / * 1 * / font-size: 100%; / * 1 * / line-height: 1.15; / * 1 * / margin: 0; / * 2 * /} button,input {/ * 1 * / overflow: visible;} button,select {/ * 1 * / text-transform: none } button,html [type= "button"], / * 1 * / [type= "reset"], [type= "submit"] {- webkit-appearance: button; / * 2 * /} button::-moz-focus-inner, [type= "button"]::-moz-focus-inner, [type= "reset"]::-moz-focus-inner, [type= "submit"]::-moz-focus-inner {border-style: none; padding: 0 } button:-moz-focusring, [type= "button"]:-moz-focusring, [type= "reset"]:-moz-focusring, [type= "submit"]:-moz-focusring {outline: 1px dotted ButtonText;} fieldset {padding: 0.35em 0.75em 0.625eme;} legend {box-sizing: border-box; / * 1 * / color: inherit; / * 2 * / display: table; / * 1 * / max-width: 100%; / * 1 * / padding: 0 / * 3 * / white-space: normal; / * 1 * /} progress {display: inline-block; / * 1 * / vertical-align: baseline; / * 2 * /} textarea {overflow: auto;} [type= "checkbox"], [type= "radio"] {box-sizing: border-box; / * 1 * / padding: 0 / * 2 * /} [type= "number"]::-webkit-inner-spin-button, [type= "number"]::-webkit-outer-spin-button {height: auto;} [type= "search"] {- webkit-appearance: textfield; / * 1 * / outline-offset:-2px; / * 2 * /} [type= "search"]::-webkit-search-cancel-button, [type= "search"]::-webkit-search-decoration {- webkit-appearance: none }:-webkit-file-upload-button {- webkit-appearance: button; / * 1 * / font: inherit; / * 2 * /} details,/* 1 * / menu {display: block;} summary {display: list-item;} canvas {display: inline-block;} template {display: none;} [hidden] {display: none } / * reset * / html,body,h2,h3,h4,h5,h6,h7,div,dl,dt,dd,ul,ol,li,p,blockquote,pre,hr,figure,table,caption,th,td,form,fieldset,legend,input,button,textarea,menu {margin: 0; padding: 0; box-sizing: border-box;} frontend technology sharing: [Q group-784783012] (http://u6.gg/eUpjy)

2. Phone-reset

/ * normalize.css * / html {line-height: 1.15; / * 1 * /-ms-text-size-adjust: 100%; / * 2 * /-webkit-text-size-adjust: 100%; / * 2 * /} body {margin: 0;} article,aside,footer,header,nav,section {display: block;} H2 {font-size: 2em; margin: 0.67em 0;} figcaption,figure,main {/ * 1 * / display: block } figure {margin: 1em 40px;} hr {box-sizing: content-box; / * 1 * / height: 0; / * 1 * / overflow: visible; / * 2 * /} pre {font-family: monospace, monospace; / * 1 * / font-size: 1em; / * 2 * /} a {background-color: transparent; / * 1 * /-webkit-text-decoration-skip: objects; / * 2 * /} abbre [title] {border-bottom: none / * 1 * / text-decoration: underline; / * 2 * / text-decoration: underline dotted; / * 2 * /} b strong {font-weight: inherit;} b strong {font-weight: bolder;} code,kbd,samp {font-family: monospace, monospace; / * 1 * / font-size: 1em; / * 2 * /} dfn {font-style: italic;} mark {background-color: # ff0; color: # 000;} small {font-size: 80 } sub,sup {font-size: 75%; line-height: 0; position: relative; vertical-align: baseline;} sub {bottom:-0.25em;} sup {top:-0.5emm;} audio,video {display: inline-block;} audio:not ([controls]) {display: none; height: 0;} img {border-style: none;} svg:not (: root) {overflow: hidden } button,input,optgroup,select,textarea {font-family: sans-serif; / * 1 * / font-size: 100%; / * 1 * / line-height: 1.15; / * 1 * / margin: 0; / * 2 * /} button,input {/ * 1 * / overflow: visible;} button,select {/ * 1 * / text-transform: none } button,html [type= "button"], / * 1 * / [type= "reset"], [type= "submit"] {- webkit-appearance: button; / * 2 * /} button::-moz-focus-inner, [type= "button"]::-moz-focus-inner, [type= "reset"]::-moz-focus-inner, [type= "submit"]::-moz-focus-inner {border-style: none; padding: 0 } button:-moz-focusring, [type= "button"]:-moz-focusring, [type= "reset"]:-moz-focusring, [type= "submit"]:-moz-focusring {outline: 1px dotted ButtonText;} fieldset {padding: 0.35em 0.75em 0.625eme;} legend {box-sizing: border-box; / * 1 * / color: inherit; / * 2 * / display: table; / * 1 * / max-width: 100%; / * 1 * / padding: 0 / * 3 * / white-space: normal; / * 1 * /} progress {display: inline-block; / * 1 * / vertical-align: baseline; / * 2 * /} textarea {overflow: auto;} [type= "checkbox"], [type= "radio"] {box-sizing: border-box; / * 1 * / padding: 0 / * 2 * /} [type= "number"]::-webkit-inner-spin-button, [type= "number"]::-webkit-outer-spin-button {height: auto;} [type= "search"] {- webkit-appearance: textfield; / * 1 * / outline-offset:-2px; / * 2 * /} [type= "search"]::-webkit-search-cancel-button, [type= "search"]::-webkit-search-decoration {- webkit-appearance: none }:-webkit-file-upload-button {- webkit-appearance: button; / * 1 * / font: inherit; / * 2 * /} details,/* 1 * / menu {display: block;} summary {display: list-item;} canvas {display: inline-block;} template {display: none;} [hidden] {display: none } / * reset * / html,body,h2,h3,h4,h5,h6,h7,div,dl,dt,dd,ul,ol,li,p,blockquote,pre,hr,figure,table,caption,th,td,form,fieldset,legend,input,button,textarea,menu {margin: 0; padding: 0; box-sizing: border-box;} html,body {/ * disable text * /-webkit-user-select: none; user-select: none Font: Oswald, 'Open Sans', Helvetica, Arial, sans-serif} / * prohibit long-press links and picture pop-up menus * / a webkit-touch-callout IMG {- webkit-touch-callout: none;} / * ios android style for removing shadows * / a field input {- webkit-tap-highlight-color: rgba (0,0,0,0);} input [type= "text"] {- webkit-appearance: none } frontend technology sharing: [Q group-784783012] (http://u6.gg/eUpjy)

2. Phone-reset

/ * normalize.css * / html {line-height: 1.15; / * 1 * /-ms-text-size-adjust: 100%; / * 2 * /-webkit-text-size-adjust: 100%; / * 2 * /} body {margin: 0;} article,aside,footer,header,nav,section {display: block;} H2 {font-size: 2em; margin: 0.67em 0;} figcaption,figure,main {/ * 1 * / display: block } figure {margin: 1em 40px;} hr {box-sizing: content-box; / * 1 * / height: 0; / * 1 * / overflow: visible; / * 2 * /} pre {font-family: monospace, monospace; / * 1 * / font-size: 1em; / * 2 * /} a {background-color: transparent; / * 1 * /-webkit-text-decoration-skip: objects; / * 2 * /} abbre [title] {border-bottom: none / * 1 * / text-decoration: underline; / * 2 * / text-decoration: underline dotted; / * 2 * /} b strong {font-weight: inherit;} b strong {font-weight: bolder;} code,kbd,samp {font-family: monospace, monospace; / * 1 * / font-size: 1em; / * 2 * /} dfn {font-style: italic;} mark {background-color: # ff0; color: # 000;} small {font-size: 80 } sub,sup {font-size: 75%; line-height: 0; position: relative; vertical-align: baseline;} sub {bottom:-0.25em;} sup {top:-0.5emm;} audio,video {display: inline-block;} audio:not ([controls]) {display: none; height: 0;} img {border-style: none;} svg:not (: root) {overflow: hidden } button,input,optgroup,select,textarea {font-family: sans-serif; / * 1 * / font-size: 100%; / * 1 * / line-height: 1.15; / * 1 * / margin: 0; / * 2 * /} button,input {/ * 1 * / overflow: visible;} button,select {/ * 1 * / text-transform: none } button,html [type= "button"], / * 1 * / [type= "reset"], [type= "submit"] {- webkit-appearance: button; / * 2 * /} button::-moz-focus-inner, [type= "button"]::-moz-focus-inner, [type= "reset"]::-moz-focus-inner, [type= "submit"]::-moz-focus-inner {border-style: none; padding: 0 } button:-moz-focusring, [type= "button"]:-moz-focusring, [type= "reset"]:-moz-focusring, [type= "submit"]:-moz-focusring {outline: 1px dotted ButtonText;} fieldset {padding: 0.35em 0.75em 0.625eme;} legend {box-sizing: border-box; / * 1 * / color: inherit; / * 2 * / display: table; / * 1 * / max-width: 100%; / * 1 * / padding: 0 / * 3 * / white-space: normal; / * 1 * /} progress {display: inline-block; / * 1 * / vertical-align: baseline; / * 2 * /} textarea {overflow: auto;} [type= "checkbox"], [type= "radio"] {box-sizing: border-box; / * 1 * / padding: 0 / * 2 * /} [type= "number"]::-webkit-inner-spin-button, [type= "number"]::-webkit-outer-spin-button {height: auto;} [type= "search"] {- webkit-appearance: textfield; / * 1 * / outline-offset:-2px; / * 2 * /} [type= "search"]::-webkit-search-cancel-button, [type= "search"]::-webkit-search-decoration {- webkit-appearance: none }:-webkit-file-upload-button {- webkit-appearance: button; / * 1 * / font: inherit; / * 2 * /} details,/* 1 * / menu {display: block;} summary {display: list-item;} canvas {display: inline-block;} template {display: none;} [hidden] {display: none } / * reset * / html,body,h2,h3,h4,h5,h6,h7,div,dl,dt,dd,ul,ol,li,p,blockquote,pre,hr,figure,table,caption,th,td,form,fieldset,legend,input,button,textarea,menu {margin: 0; padding: 0; box-sizing: border-box;} html,body {/ * disable text * /-webkit-user-select: none; user-select: none Font: Oswald, 'Open Sans', Helvetica, Arial, sans-serif} / * prohibit long-press links and picture pop-up menus * / a webkit-touch-callout IMG {- webkit-touch-callout: none;} / * ios android style for removing shadows * / a field input {- webkit-tap-highlight-color: rgba (0,0,0,0);} input [type= "text"] {- webkit-appearance: none;}

3. Common style extraction

/ * disable the selected text * / .usn {- webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o Rose user select content; user-select:none;} / * floating * / .fl {float: left;}. Fr {float: right;}. Cf {zoom: 1;}. Cf:after {content: ".; display:block; clear:both Visibility:hidden; height:0; overflow:hidden;} / * element type * / .db {display: block;}. Dn {display: none;}. Di {display: inline}. Dib {display: inline-block } .transparent {opacity: 0} / * text typesetting, color * / .f12 {font-size:12px} .f14 {font-size:14px} .f16 {font-size:16px} .f18 {font-size:18px} .f20 {font-size:20px} .fb {font-weight:bold} .fn {font-weight:normal} .t2 {text-indent:2em} .red, a.red {color:#cc0031} .blue, a.darkblue {color:#039} .gray A.gray {color:#878787}. Lh250 {line-height:150%}. Lh280 {line-height:180%}. Lh300 {line-height:200%}. Unl {text-decoration:underline }. No_unl {text-decoration:none;}. Tl {text-align: left;}. Tc {text-align: center;}. Tr {text-align: right;}. Tj {text-align: justify; text-justify: inter-ideograph;}. Wn {/ * forcibly do not wrap * / word-wrap:normal; white-space:nowrap;}. Wb {/ * force line wrapping * / white-space:normal; word-wrap:break-word Word-break:break-all;}. Wp {/ * keep blank sequence * / overflow:hidden;text-align:left;white-space:pre-wrap;word-wrap:break-word;word-break:break-all;}. Wes {/ * excess is indicated by an ellipsis for one line * / overflow:hidden; word-wrap:normal; white-space:nowrap; text-overflow:ellipsis }. Wes-2 {/ * for webkit kernel and mobile * / display:-webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2; overflow: hidden;} .wes-3 {display:-webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3; overflow: hidden;}. Wes-4 {display:-webkit-box -webkit-box-orient: vertical;-webkit-line-clamp: 4; overflow: hidden;} / * overflow style * / .ofh {overflow: hidden;}. Ofs {overflow: scroll;}. Ofa {overflow: auto;}. Ofv {overflow: visible;} / * location method * / .ps {position: static;}. Pr {position: relative;zoom:1;}. Pa {position: absolute;}. Pf {position: fixed } / * Vertical alignment * / .vt {vertical-align: top;}. Vm {vertical-align: middle;}. Vb {vertical-align: bottom;} / * mouse style * / .csd {cursor: default;}. Csp {cursor: pointer;}. Csh {cursor: help;}. Csm {cursor: move;} / * flex layout * / .df-sb {display:flex; align-items: center; justify-content: space-between }. Df-sa {display:flex; align-items: center; justify-content: space-around;} / * Vertical Center * / .df-c {display:flex; align-items: center; justify-content: center;}. Tb-c {text-align:center; display:table-cell; vertical-align:middle;}. Ts-c {position: absolute; left: 50%; top: 50% Transform: translate (- 50%,-50%);}. Ts-mc {position: absolute; left:0; right: 0; bottom: 0 width 0; margin: auto;} / * Auxiliary * / .mask-fixed-wrapper {width: 100%; height: 100%; position: fixed; left:0;top:0; background: rgba (0,0,0,0.65); z-index: 999 }. Bg-cover {background-size: cover; background-repeat: no-repeat; background-position: center center;} .bg-cover-all {background-size: 100% 100%; background-repeat: no-repeat; background-position: center center;} "sharing a tutorial on encapsulation of common tools and methods for JavaScript and CSS" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report