JavaScript常用工具方法封装
程序员文章站
2022-05-17 14:51:29
因为工作中经常用到这些方法,所有便把这些方法进行了总结。
javascript
1. type 类型判断
isstring (o) { //是否字符串...
因为工作中经常用到这些方法,所有便把这些方法进行了总结。
javascript
1. type 类型判断
isstring (o) { //是否字符串 return object.prototype.tostring.call(o).slice(8, -1) === 'string' } isnumber (o) { //是否数字 return object.prototype.tostring.call(o).slice(8, -1) === 'number' } isboolean (o) { //是否boolean return object.prototype.tostring.call(o).slice(8, -1) === 'boolean' } isfunction (o) { //是否函数 return object.prototype.tostring.call(o).slice(8, -1) === 'function' } isnull (o) { //是否为null return object.prototype.tostring.call(o).slice(8, -1) === 'null' } isundefined (o) { //是否undefined 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' } issymbol (o) { //是否symbol函数 return object.prototype.tostring.call(o).slice(8, -1) === 'symbol' } ispromise (o) { //是否promise对象 return object.prototype.tostring.call(o).slice(8, -1) === 'promise' } isset (o) { //是否set对象 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) {//安卓手机 // return "android"; return false } else if (u.indexof('iphone') > -1) {//苹果手机 // return "iphone"; return true } else if (u.indexof('ipad') > -1) {//ipad // return "ipad"; return false } else if (u.indexof('windows phone') > -1) {//winphone手机 // return "windows phone"; return false }else{ return false } } ispc () { //是否为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; //取得浏览器的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") > -1; var 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" else if(fieversion == 8) return "ie8"; else if(fieversion == 9) return "ie9"; else if(fieversion == 10) return "ie10"; else 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|9][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': //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线 return /^[a-za-z]\w{5,17}$/.test(str) case 'postal': //邮政编码 return /[1-9]\d{5}(?!\d)/.test(str); case 'qq': //qq号 return /^[1-9][0-9]{4,9}$/.test(str); case 'email': //邮箱 return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case 'money': //金额(小数点2位) return /^\d*(?:\.\d{0,2})?$/.test(str); case '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': //日期时间 return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str) case 'number': //数字 return /^[0-9]$/.test(str); case 'english': //英文 return /^[a-za-z]+$/.test(str); case 'chinese': //中文 return /^[\u4e00-\u9fa5]+$/.test(str); case 'lower': //小写 return /^[a-z]+$/.test(str); case 'upper': //大写 return /^[a-z]+$/.test(str); case 'html': //html标记 return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str); default: return true; } // 严格的身份证校验 iscardid(sid) { if (!/(^\d{15}$)|(^\d{17}(\d|x|x)$)/.test(sid)) { alert('你输入的身份证长度或格式错误') 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))]) { alert('你的身份证地区非法') 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())) { alert('身份证上的出生日期非法') 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]; //计算出来的最后一位身份证号码 if (sid[sid.length-1] != last) { alert('你输入的身份证号非法') return false } return true } }
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|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 }) 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 && 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(i/12), m = i%12 return [yy+y + '-' + (m+1)] } var formatpre = function(i) { var y = math.ceil(i/12), m = i%12 m = m===0 ? 12 : m return [yy-y + '-' + (13 - m)] } var formatcurr = function(i) { var y = math.floor(i/12), ynext = math.ceil(i/12), m = i%12, mnext = m===0 ? 12 : m return [yy-ynext + '-' + (13 - mnext),yy+y + '-' + (m+1)] } // 数组去重 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 <= len; i++) { arr.unshift(getday(-i)) } }else if(diretion === 2) { for (var i = 1; i <= len; i++) { arr.push(getday(i)) } }else { for (var i = 1; i <= len; i++) { arr.unshift(getday(-i)) } arr.push(tt.getfullyear()+'-'+(tt.getmonth()+1)+'-'+tt.getdate()) for (var i = 1; i <= len; i++) { 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' }else if(s > 60) { str = math.floor(s/60)+'m'+s%60+'s' }else{ str = s%60+'s' } return str } /*获取某月有多少天*/ getmonthofday (time) { var date = new date(time) 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 : 29 } else if (mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth == 12) { //月份为:1,3,5,7,8,10,12 时,为大月.则天数为31; days = 31 } else { //其他月份,天数为:30. days = 30 } return days } /*获取某年有多少天*/ getyearofday (time) { var firstdayyear = this.getfirstdayofyear(time); var lastdayyear = this.getlastdayofyear(time); var numsecond = (new date(lastdayyear).gettime() - new date(firstdayyear).gettime())/1000; return math.ceil(numsecond/(24*3600)); } /*获取某年的第一天*/ getfirstdayofyear (time) { var year = new date(time).getfullyear(); return year + "-01-01 00:00:00"; } /*获取某年最后一天*/ getlastdayofyear (time) { var year = new date(time).getfullyear(); var datestring = year + "-12-01 00:00:00"; var endday = this.getmonthofday(datestring); return year + "-12-" + endday + " 23:59:59"; } /*获取某个日期是当年中的第几天*/ getdayofyear (time) { var firstdayyear = this.getfirstdayofyear(time); var numsecond = (new date(time).gettime() - new date(firstdayyear).gettime())/1000; return math.ceil(numsecond/(24*3600)); } /*获取某个日期在这一年的第几周*/ getdayofyearweek (time) { var numdays = this.getdayofyear(time); return math.ceil(numdays / 7); }
3. array
/*判断一个元素是否在数组中*/ contains (arr, val) { return arr.indexof(val) != -1 ? true : false; } /** * @param {arr} 数组 * @param {fn} 回调函数 * @return {undefined} */ each (arr, fn) { fn = fn || function; var a = []; var args = array.prototype.slice.call(arguments, 1); for(var i = 0; i < arr.length; i++) { 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 a = []; for(var i = 0, j = arr.length; i < j; ++i) { var res = fn.call(scope, arr[i], i, this); if(res != null) a.push(res); } return a; } /** * @param {arr} 数组 * @param {type} 1:从小到大 2:从大到小 3:随机 * @return {array} */ sort (arr, type = 1) { 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; } }) } /*去重*/ 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; } /*将类数组转换为数组的方法*/ formarray (ary) { var arr = []; if(array.isarray(ary)) { arr = ary; } else { arr = array.prototype.slice.call(ary); }; return arr; } /*最大值*/ max (arr) { return math.max.apply(null, arr); } /*最小值*/ min (arr) { return math.min.apply(null, arr); } /*求和*/ sum (arr) { return arr.reduce( (pre, cur) => { return pre + cur }) } /*平均值*/ average (arr) { return this.sum(arr)/arr.length }
4. string 字符串操作
/** * 去除空格 * @param {str} * @param {type} * type: 1-所有空格 2-前后空格 3-前空格 4-后空格 * @return {string} */ 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; } } /** * @param {str} * @param {type} * type: 1:首字母大写 2:首页母小写 3:大小写转换 4:全部大写 5:全部小写 * @return {string} */ changecase (str, type) { type = type || 4 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, 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(); default: return str; } } /* 检测密码强度 */ 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(/>/ig, ">"); str = str.replace(" ", " "); return str; }
5. number
/*随机数范围*/ random (min, max) { if (arguments.length === 2) { return math.floor(min + math.random() * ( (max+1) - min )) }else{ return null; } } /*将阿拉伯数字翻译成中文的大写数字*/ 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; } /*将数字转换为大写金额*/ 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; i--) { if(part[0].length > 10) { return ""; //若数量超过拾亿单位,提示 } var tmpnewchar = "" var perchar = part[0].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; } switch(part[0].length - i - 1) { case 0: tmpnewchar = tmpnewchar + "元"; break; case 1: if(perchar != 0) tmpnewchar = tmpnewchar + "拾"; break; case 2: if(perchar != 0) tmpnewchar = tmpnewchar + "佰"; break; case 3: if(perchar != 0) tmpnewchar = tmpnewchar + "仟"; break; case 4: tmpnewchar = tmpnewchar + "万"; break; case 5: if(perchar != 0) tmpnewchar = tmpnewchar + "拾"; break; case 6: if(perchar != 0) tmpnewchar = tmpnewchar + "佰"; break; case 7: if(perchar != 0) tmpnewchar = tmpnewchar + "仟"; break; case 8: tmpnewchar = tmpnewchar + "亿"; break; case 9: tmpnewchar = tmpnewchar + "拾"; break; } var newchar = tmpnewchar + newchar; } //小数点之后进行转化 if(num.indexof(".") != -1) { if(part[1].length > 2) { // alert("小数点之后只能保留两位,系统将自动截断"); 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) }) }) }
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) } } /*检测类名*/ hasclass (ele, name) { return ele.classname.match(new regexp('(\\s|^)' + name + '(\\s|$)')); } /*添加类名*/ addclass (ele, name) { if (!this.hasclass(ele, name)) ele.classname += " " + name; } /*删除类名*/ removeclass (ele, name) { if (this.hasclass(ele, name)) { var reg = new regexp('(\\s|^)' + name + '(\\s|$)'); ele.classname = ele.classname.replace(reg, ''); } } /*替换类名*/ replaceclass (ele, newname, oldname) { this.removeclass(ele, oldname); this.addclass(ele, newname); } /*获取兄弟节点*/ siblings (ele) { console.log(ele.parentnode) var chid = ele.parentnode.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); document.cookie = i + '=' + setting[i] + ';expires=' + odate; } }else{ var odate = new date(); odate.setdate(odate.getdate() + day); document.cookie = name + '=' + value + ';expires=' + odate; } } /*获取cookie*/ getcookie (name) { var arr = document.cookie.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; i++) { 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; } } /*获取十六进制随机颜色*/ getrandomcolor () { return '#' + (function(h) { return new array(7 - h.length).join("0") + h; })((math.random() * 0x1000000 << 0).tostring(16)); } /*图片加载*/ imgloadall(arr,callback){ var arrimg = []; for (var i = 0; i < arr.length; i++) { var img = new image(); img.src = arr[i]; img.onload = function(){ arrimg.push(this); if (arrimg.length == arr.length) { callback && callback(); } } } } /*音频加载*/ loadaudio(src, callback) { var audio = new audio(src); audio.onloadedmetadata = callback; audio.src = src; } /*dom转字符串*/ domtostirng(htmldom){ var div= document.createelement("div"); div.appendchild(htmldom); return div.innerhtml } /*字符串转dom*/ stringtodom(htmlstring){ var div= document.createelement("div"); div.innerhtml=htmlstring; return div.children[0]; } /** * 光标所在位置插入字符,并设置光标位置 * @param {dom} 输入框 * @param {val} 插入的值 * @param {poslen} 光标位置处在 插入的值的哪个位置 */ setcursorposition (dom,val,poslen) { var cursorposition = 0; if(dom.selectionstart){ cursorposition = dom.selectionstart; } this.insertatcursor(dom,val); dom.focus(); console.log(poslen) dom.setselectionrange(dom.value.length,cursorposition + (poslen || val.length)); } /*光标所在位置插入字符*/ insertatcursor(dom, val) { if (document.selection){ dom.focus(); sel = document.selection.createrange(); sel.text = val; sel.select(); }else 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; } else { dom.value += val; dom.focus(); } }
css
1. pc-reset pc样式初始化
/* 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; } h1 { 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 */ } abbr[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.5em; } 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.625em; } 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, h1, h2, h3, h4, h5, h6, 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; }
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; } h1 { 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 */ } abbr[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.5em; } 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.625em; } 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, h1, h2, h3, h4, h5, h6, 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 { /* 禁止选中文本 */ -webkit-user-select: none; user-select: none; font: oswald, 'open sans', helvetica, arial, sans-serif } /* 禁止长按链接与图片弹出菜单 */ a, img { -webkit-touch-callout: none; } /*ios android去除自带阴影的样式*/ a, input { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } input[type="text"] { -webkit-appearance: none; }
3. 公共样式提取
/* 禁止选中文本 */ .usn{ -webkit-user-select:none; -moz-user-select:none; -ms-user-select:none; -o-user-select:none; user-select:none; } /* 浮动 */ .fl { float: left; } .fr { float: right; } .cf { zoom: 1; } .cf:after { content:"."; display:block; clear:both; visibility:hidden; height:0; overflow:hidden; } /* 元素类型 */ .db { display: block; } .dn { display: none; } .di { display: inline } .dib {display: inline-block;} .transparent { opacity: 0 } /*文字排版、颜色*/ .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 } .darkblue,a.darkblue { color:#039 } .gray,a.gray { color:#878787 } .lh150 { line-height:150% } .lh180 { line-height:180% } .lh200 { 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 { /* 强制不换行 */ word-wrap:normal; white-space:nowrap; } .wb { /* 强制换行 */ white-space:normal; word-wrap:break-word; word-break:break-all; } .wp { /* 保持空白序列*/ overflow:hidden;text-align:left;white-space:pre-wrap;word-wrap:break-word;word-break:break-all; } .wes { /* 多出部分用省略号表示 , 用于一行 */ overflow:hidden; word-wrap:normal; white-space:nowrap; text-overflow:ellipsis; } .wes-2 { /* 适用于webkit内核和移动端 */ 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; } /* 溢出样式 */ .ofh { overflow: hidden; } .ofs {overflow: scroll; } .ofa {overflow: auto; } .ofv {overflow: visible; } /* 定位方式 */ .ps {position: static; } .pr {position: relative;zoom:1; } .pa {position: absolute; } .pf {position: fixed; } /* 垂直对齐方式 */ .vt {vertical-align: top; } .vm {vertical-align: middle; } .vb {vertical-align: bottom; } /* 鼠标样式 */ .csd {cursor: default; } .csp {cursor: pointer; } .csh {cursor: help; } .csm {cursor: move; } /* flex布局 */ .df-sb { display:flex; align-items: center; justify-content: space-between; } .df-sa { display:flex; align-items: center; justify-content: space-around; } /* 垂直居中 */ .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; top: 0; margin: auto; } /* 辅助 */ .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; }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
推荐阅读
-
避免回车键导致的页面无意义刷新的解决方法_javascript技巧
-
jQuery常用工具方法
-
编写js扩展方法判断一个数组中是否包含某个元素_javascript技巧
-
js实现从中间开始往上下展开网页窗口的方法_javascript技巧
-
九种js弹出对话框的方法总结_javascript技巧
-
javascript 操作文件 实现方法小结_javascript技巧
-
实现lightBox时的样式与行为分离减少JS_javascript技巧单行居中,多行居左未知高度垂直居中的方法
-
javascript对数组的常用操作代码 数组方法总汇_javascript技巧
-
javascript - JS中有类似PHP date()方法吗?
-
php与javascript正则匹配中文的方法实现详解