js工具函数大全
校验是否包含中文字符(包括中文标点符号)
1 function haveCNChars(str){ 2 return /[\u4e00-\u9fa5]/.test(str); 3 }
校验是否包含空格
1 function haveSpace(str) { 2 return /[ ]/.test(str); 3 }
除保留标点符号集以外,清除其他所有英文的标点符号(含空格)
- 全部英文标点符号为:~`!@#$%^&*()-_+=[]{};:"',<.>/?
- 参数excludePunctuation指需要保留的标点符号集,例如若传递的值为'_',即表示清除_以外的其他所有英文标点符号。
1 function clearPunctuation(str,excludePunctuation=null){ 2 let regexp = new RegExp(`[${getExcludePunctuation(excludePunctuation)}]`,'g'); 3 return str.replace(regexp,''); 4 }
清除所有中文字符及空格
1 function clearCNCharsAndSpaces(str){ 2 return str.replace(/[\u4e00-\u9fa5 ]/g,''); 3 }
清除所有中文字符(包括中文标点符号)
1 function clearCNChars(str){ 2 return str.replace(/[\u4e00-\u9fa5]/g,''); 3 }
清除所有空格
1 function clearSpaces(str){ 2 return str.replace(/[ ]/g,''); 3 }
校验字符串构成的种类数量是否大于或等于参数num的值。通常用来校验用户设置的密码复杂程度。
校验规则:
- 参数num为需要构成的种类(字母、数字、标点符号),该值只能是1-3。
- 默认参数num的值为1,即表示:至少包含字母,数字,标点符号中的1种
- 若参数num的值为2,即表示:至少包含字母,数字,标点符号中的2种
- 若参数num的值为3,即表示:必须同时包含字母,数字,标点符号
- 参数punctuation指可接受的标点符号集,具体设定可参考getLIPTypes()方法中关于标点符号集的解释。
1 function pureLIP(str,num=1,punctuation=null){ 2 let regexp = new RegExp(`[^A-z0-9|${getPunctuation(punctuation)}]`); 3 return Boolean(!regexp.test(str) && getLIPTypes(str,punctuation)>= num); 4 }
返回字符串构成种类(字母,数字,标点符号)的数量
LIP缩写的由来:L(letter 字母) + I(uint 数字) + P(punctuation 标点符号)
参数punctuation的说明:
- punctuation指可接受的标点符号集
- 若需自定义符号集,例如“仅包含中划线和下划线”,将参数设置为"-_"即可
- 若不传值或默认为null,则内部默认标点符号集为除空格外的其他英文标点符号:~`!@#$%^&*()-_+=[]{};:"',<.>/?
1 function getLIPTypes(str,punctuation=null){ 2 let p_regexp = new RegExp('['+getPunctuation(punctuation)+']'); 3 return /[A-z]/.test(str) + /[0-9]/.test(str) + p_regexp.test(str); 4 }
校验字符是否为纯数字(整数)
校验规则:
- 字符全部为正整数(包含0)
- 可以以0开头
1 function pureNum(str) { 2 return /^[0-9]*$/.test(str); 3 } 4 function anysicPunctuation(str){ 5 if(!str) return null; 6 let arr = str.split('').map(item => { 7 return item = '\\' + item; 8 }); 9 return arr.join('|'); 10 } 11 function getPunctuation(str){ 12 return anysicPunctuation(str) || '\\~|\\`|\\!|\\@|\\#|\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\-|\\_|\\+|\\=|\\||\\\|\\[|\\]|\\{|\\}|\\;|\\:|\\"|\\\'|\\,|\\<|\\.|\\>|\\/|\\?'; 13 } 14 function getExcludePunctuation(str){ 15 let regexp = new RegExp(`[${anysicPunctuation(str)}]`,'g'); 16 return getPunctuation(' ~`!@#$%^&*()-_+=\[]{};:"\',<.>/?'.replace(regexp,'')); 17 }
校验字符是否以字母开头
校验规则:
- 必须以字母开头
- 开头的字母不区分大小写
1 function letterBegin(str){ 2 return /^[A-z]/.test(str); 3 }
校验字符的长度是否在规定的范围内
校验规则:
- minInt为在取值范围中最小的长度
- maxInt为在取值范围中最大的长度
1 function lengthRange(str,minLength,maxLength=9007199254740991) { 2 return Boolean(str.length >= minLength && str.length <= maxLength); 3 }
校验两个参数是否完全相同,包括类型
校验规则:
- 值相同,数据类型也相同
1 function same(firstValue,secondValue){ 2 return firstValue===secondValue; 3 }
校验是否为中国大陆邮政编码
参数value为数字或字符串,校验规则:
- 共6位,且不能以0开头
1 function isPostCode(value){ 2 return /^[1-9][0-9]{5}$/.test(value.toString()); 3 }
校验是否为中国大陆第二代居民身份证
校验规则:
- 共18位,最后一位可为X(大小写均可)
- 不能以0开头
- 出生年月日会进行校验:年份只能为18/19/2*开头,月份只能为01-12,日只能为01-31
1 function isIDCard(str){ 2 return /^[1-9][0-9]{5}(18|19|(2[0-9]))[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}[0-9Xx]$/.test(str); 3 }
校验是否为IPv6地址
校验规则:
- 支持IPv6正常格式
- 支持IPv6压缩格式
1 function isIPv6(str){ 2 return Boolean(str.match(/:/g)?str.match(/:/g).length<=7:false && /::/.test(str)?/^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$/i.test(str):/^([\da-f]{1,4}:){7}[\da-f]{1,4}$/i.test(str)); 3 }
校验是否为不含端口号的IP地址
校验规则:
- IP格式为xxx.xxx.xxx.xxx,每一项数字取值范围为0-255
- 除0以外其他数字不能以0开头,比如02
1 function isIP(str) { 2 return /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/.test(str); 3 }
校验是否为网址
校验规则:
- 以https://、http://、ftp://、rtsp://、mms://开头、或者没有这些开头
- 可以没有www开头(或其他二级域名),仅域名
- 网页地址中允许出现/%*?@&等其他允许的符号
1 function isURL(str) { 2 return /^(https:\/\/|http:\/\/|ftp:\/\/|rtsp:\/\/|mms:\/\/)?[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test(str); 3 }
校验是否为QQ号码
校验规则:
1 //非0开头的5位-13位整数 2 function isQQ(value) { 3 return /^[1-9][0-9]{4,12}$/.test(value.toString()); 4 }
校验是否为邮箱地址
1 function isEmail(str) { 2 return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(str); 3 }
校验是否为中国大陆传真或固定电话号码
1 function isFax(str) { 2 return /^([0-9]{3,4})?[0-9]{7,8}$|^([0-9]{3,4}-)?[0-9]{7,8}$/.test(str); 3 }
校验是否为中国大陆手机号
1 function isTel(value) { 2 return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString()); 3 }
校验整数是否在取值范围内
校验规则:
- minInt为在取值范围中最小的整数
- maxInt为在取值范围中最大的整数
1 function checkIntRange(value,minInt,maxInt=9007199254740991){ 2 return Boolean(isInt(value) && (Boolean(minInt!=undefined && minInt!=null)?value>=minInt:true) && (value<=maxInt)); 3 }
校验是否为非零的负整数
1 function isNInt(value,minLength=null,maxLength=undefined){ 2 if(!isNum(value)) return false; 3 let regexp = new RegExp(`^-[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`); 4 return regexp.test(value.toString()); 5 }
校验是否为非零的正整数
1 function isPInt(value,minLength=null,maxLength=undefined) { 2 if(!isNum(value)) return false; 3 4 let regexp = new RegExp(`^[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`); 5 return regexp.test(value.toString()); 6 }
校验是否为非零的正整数
1 function isInt(value,minLength=null,maxLength=undefined){ 2 if(!isNum(value)) return false; 3 4 let regexp = new RegExp(`^-?[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`); 5 return regexp.test(value.toString()); 6 }
常见的输入值校验和替换操作,主要针对中国大陆地区的校验规则:
校验是否为一个数字,以及该数字小数点位数是否与参数floats一致 校验规则:
- 若参数floats有值,则校验该数字小数点后的位数。
- 若参数floats没有值,则仅仅校验是否为数字。
1 function isNum(value,floats=null){ 2 let regexp = new RegExp(`^[1-9][0-9]*.[0-9]{${floats}}$|^0.[0-9]{${floats}}$`); 3 return typeof value === 'number' && floats?regexp.test(String(value)):true; 4 } 5 function anysicIntLength(minLength,maxLength){ 6 let result_str = ''; 7 if(minLength){ 8 switch(maxLength){ 9 case undefined: 10 result_str = result_str.concat(`{${minLength-1}}`); 11 break; 12 case null: 13 result_str = result_str.concat(`{${minLength-1},}`); 14 break; 15 default: 16 result_str = result_str.concat(`{${minLength-1},${maxLength-1}}`); 17 } 18 }else{ 19 result_str = result_str.concat('*'); 20 } 21 22 return result_str; 23 }
实现utf8解码
1 function utf8_decode(str_data) { 2 var tmp_arr = [], 3 i = 0, 4 ac = 0, 5 c1 = 0, 6 c2 = 0, 7 c3 = 0; 8 str_data += ""; 9 while (i < str_data.length) { 10 c1 = str_data.charCodeAt(i); 11 if (c1 < 128) { 12 tmp_arr[ac++] = String.fromCharCode(c1); 13 i++; 14 } else if (c1 > 191 && c1 < 224) { 15 c2 = str_data.charCodeAt(i + 1); 16 tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); 17 i += 2; 18 } else { 19 c2 = str_data.charCodeAt(i + 1); 20 c3 = str_data.charCodeAt(i + 2); 21 tmp_arr[ac++] = String.fromCharCode( 22 ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63) 23 ); 24 i += 3; 25 } 26 } 27 return tmp_arr.join(""); 28 }
随机数时间戳
1 function uniqueId() { 2 var a = Math.random, 3 b = parseInt; 4 return ( 5 Number(new Date()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a()) 6 ); 7 }
清除空格
1 String.prototype.trim = function() { 2 var reExtraSpace = /^\s*(.*?)\s+$/; 3 return this.replace(reExtraSpace, "$1"); 4 }; 5 6 // 清除左空格 7 function ltrim(s) { 8 return s.replace(/^(\s*| *)/, ""); 9 } 10 11 // 清除右空格 12 function rtrim(s) { 13 return s.replace(/(\s*| *)$/, ""); 14 }
金额大写转换函数
1 function transform(tranvalue) { 2 try { 3 var i = 1; 4 var dw2 = new Array("", "万", "亿"); //大单位 5 var dw1 = new Array("拾", "佰", "仟"); //小单位 6 var dw = new Array( 7 "零", 8 "壹", 9 "贰", 10 "叁", 11 "肆", 12 "伍", 13 "陆", 14 "柒", 15 "捌", 16 "玖" 17 ); 18 //整数部分用 19 //以下是小写转换成大写显示在合计大写的文本框中 20 //分离整数与小数 21 var source = splits(tranvalue); 22 var num = source[0]; 23 var dig = source[1]; 24 //转换整数部分 25 var k1 = 0; //计小单位 26 var k2 = 0; //计大单位 27 var sum = 0; 28 var str = ""; 29 var len = source[0].length; //整数的长度 30 for (i = 1; i <= len; i++) { 31 var n = source[0].charAt(len - i); //取得某个位数上的数字 32 var bn = 0; 33 if (len - i - 1 >= 0) { 34 bn = source[0].charAt(len - i - 1); //取得某个位数前一位上的数字 35 } 36 sum = sum + Number(n); 37 if (sum != 0) { 38 str = dw[Number(n)].concat(str); //取得该数字对应的大写数字,并插入到str字符串的前面 39 if (n == "0") sum = 0; 40 } 41 if (len - i - 1 >= 0) { 42 //在数字范围内 43 if (k1 != 3) { 44 //加小单位 45 if (bn != 0) { 46 str = dw1[k1].concat(str); 47 } 48 k1++; 49 } else { 50 //不加小单位,加大单位 51 k1 = 0; 52 var temp = str.charAt(0); 53 if (temp == "万" || temp == "亿") 54 //若大单位前没有数字则舍去大单位 55 str = str.substr(1, str.length - 1); 56 str = dw2[k2].concat(str); 57 sum = 0; 58 } 59 } 60 if (k1 == 3) { 61 //小单位到千则大单位进一 62 k2++; 63 } 64 } 65 //转换小数部分 66 var strdig = ""; 67 if (dig != "") { 68 var n = dig.charAt(0); 69 if (n != 0) { 70 strdig += dw[Number(n)] + "角"; //加数字 71 } 72 var n = dig.charAt(1); 73 if (n != 0) { 74 strdig += dw[Number(n)] + "分"; //加数字 75 } 76 } 77 str += "元" + strdig; 78 } catch (e) { 79 return "0元"; 80 } 81 return str; 82 } 83 //拆分整数与小数 84 function splits(tranvalue) { 85 var value = new Array("", ""); 86 temp = tranvalue.split("."); 87 for (var i = 0; i < temp.length; i++) { 88 value = temp; 89 } 90 return value; 91 }
半角转换为全角函数
1 function toDBC(str) { 2 var result = ""; 3 for (var i = 0; i < str.length; i++) { 4 code = str.charCodeAt(i); 5 if (code >= 33 && code <= 126) { 6 result += String.fromCharCode(str.charCodeAt(i) + 65248); 7 } else if (code == 32) { 8 result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32); 9 } else { 10 result += str.charAt(i); 11 } 12 } 13 return result; 14 }
全角转换为半角函数
1 function toCDB(str) { 2 var result = ""; 3 for (var i = 0; i < str.length; i++) { 4 code = str.charCodeAt(i); 5 if (code >= 65281 && code <= 65374) { 6 result += String.fromCharCode(str.charCodeAt(i) - 65248); 7 } else if (code == 12288) { 8 result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32); 9 } else { 10 result += str.charAt(i); 11 } 12 } 13 return result; 14 }
时间个性化输出功能
1 /* 2 1、< 60s, 显示为“刚刚” 3 2、>= 1min && < 60 min, 显示与当前时间差“XX分钟前” 4 3、>= 60min && < 1day, 显示与当前时间差“今天 XX:XX” 5 4、>= 1day && < 1year, 显示日期“XX月XX日 XX:XX” 6 5、>= 1year, 显示具体日期“XXXX年XX月XX日 XX:XX” 7 */ 8 function timeFormat(time) { 9 var date = new Date(time), 10 curDate = new Date(), 11 year = date.getFullYear(), 12 month = date.getMonth() + 10, 13 day = date.getDate(), 14 hour = date.getHours(), 15 minute = date.getMinutes(), 16 curYear = curDate.getFullYear(), 17 curHour = curDate.getHours(), 18 timeStr; 19 20 if (year < curYear) { 21 timeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute; 22 } else { 23 var pastTime = curDate - date, 24 pastH = pastTime / 3600000; 25 26 if (pastH > curHour) { 27 timeStr = month + "月" + day + "日 " + hour + ":" + minute; 28 } else if (pastH >= 1) { 29 timeStr = "今天 " + hour + ":" + minute + "分"; 30 } else { 31 var pastM = curDate.getMinutes() - minute; 32 if (pastM > 1) { 33 timeStr = pastM + "分钟前"; 34 } else { 35 timeStr = "刚刚"; 36 } 37 } 38 } 39 return timeStr; 40 }
清除脚本内容
1 function stripscript(s) { 2 return s.replace(/<script.*?>.*?<\/script>/gi, ""); 3 }
判断是否以某个字符串开头
1 String.prototype.startWith = function(s) { 2 return this.indexOf(s) == 0; 3 };
延时执行
1 // 比如 sleep(1000) 意味着等待1000毫秒,还可从 Promise、Generator、Async/Await 等角度实现。 2 // Promise 3 const sleep = time => { 4 return new Promise(resolve => setTimeout(resolve, time)); 5 }; 6 7 sleep(1000).then(() => { 8 console.log(1); 9 }); 10 11 // Generator 12 function* sleepGenerator(time) { 13 yield new Promise(function(resolve, reject) { 14 setTimeout(resolve, time); 15 }); 16 } 17 18 sleepGenerator(1000) 19 .next() 20 .value.then(() => { 21 console.log(1); 22 }); 23 24 //async 25 function sleep(time) { 26 return new Promise(resolve => setTimeout(resolve, time)); 27 } 28 29 async function output() { 30 let out = await sleep(1000); 31 console.log(1); 32 return out; 33 } 34 35 output(); 36 37 function sleep(callback, time) { 38 if (typeof callback === "function") { 39 setTimeout(callback, time); 40 } 41 } 42 43 function output() { 44 console.log(1); 45 } 46 47 sleep(output, 1000);
按字母排序,对每行进行数组排序
1 function setSort() { 2 var text = K1.value 3 .split(/[\r\n]/) 4 .sort() 5 .join("\r\n"); //顺序 6 var test = K1.value 7 .split(/[\r\n]/) 8 .sort() 9 .reverse() 10 .join("\r\n"); //反序 11 K1.value = K1.value != text ? text : test; 12 }
设为首页
1 function setHomepage() { 2 if (document.all) { 3 document.body.style.behavior = "url(#default#homepage)"; 4 document.body.setHomePage("http://w3cboy.com"); 5 } else if (window.sidebar) { 6 if (window.netscape) { 7 try { 8 netscape.security.PrivilegeManager.enablePrivilege( 9 "UniversalXPConnect" 10 ); 11 } catch (e) { 12 alert( 13 "该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true" 14 ); 15 } 16 } 17 var prefs = Components.classes[ 18 "@mozilla.org/preferences-service;1" 19 ].getService(Components.interfaces.nsIPrefBranch); 20 prefs.setCharPref("browser.startup.homepage", "http://w3cboy.com"); 21 } 22 }
获取cookie值
1 function getCookie(name) { 2 var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); 3 if (arr != null) return unescape(arr[2]); 4 return null; 5 }
设置cookie值
1 function setCookie(name, value, Hours) { 2 var d = new Date(); 3 var offset = 8; 4 var utc = d.getTime() + d.getTimezoneOffset() * 60000; 5 var nd = utc + 3600000 * offset; 6 var exp = new Date(nd); 7 exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000); 8 document.cookie = 9 name + 10 "=" + 11 escape(value) + 12 ";path=/;expires=" + 13 exp.toGMTString() + 14 ";domain=360doc.com;"; 15 }
滚动到顶部
1 // 使用document.documentElement.scrollTop 或 document.body.scrollTop 获取到顶部的距离,从顶部 2 // 滚动一小部分距离。使用window.requestAnimationFrame()来滚动。 3 // @example 4 // scrollToTop(); 5 function scrollToTop() { 6 var c = document.documentElement.scrollTop || document.body.scrollTop; 7 8 if (c > 0) { 9 window.requestAnimationFrame(scrollToTop); 10 window.scrollTo(0, c - c / 8); 11 } 12 }
替换全部
1 String.prototype.replaceAll = function(s1, s2) { 2 return this.replace(new RegExp(s1, "gm"), s2); 3 }; 4 resize的操作 5 (function() { 6 var fn = function() { 7 var w = document.documentElement 8 ? document.documentElement.clientWidth 9 : document.body.clientWidth, 10 r = 1255, 11 b = Element.extend(document.body), 12 classname = b.className; 13 if (w < r) { 14 //当窗体的宽度小于1255的时候执行相应的操作 15 } else { 16 //当窗体的宽度大于1255的时候执行相应的操作 17 } 18 }; 19 if (window.addEventListener) { 20 window.addEventListener("resize", function() { 21 fn(); 22 }); 23 } else if (window.attachEvent) { 24 window.attachEvent("onresize", function() { 25 fn(); 26 }); 27 } 28 fn(); 29 })();
替换地址栏
1 function locationReplace(url) { 2 if (history.replaceState) { 3 history.replaceState(null, document.title, url); 4 history.go(0); 5 } else { 6 location.replace(url); 7 } 8 }
去掉url前缀
1 function removeUrlPrefix(a) { 2 a = a 3 .replace(/:/g, ":") 4 .replace(/./g, ".") 5 .replace(///g, "/"); 6 while ( 7 trim(a) 8 .toLowerCase() 9 .indexOf("http://") == 0 10 ) { 11 a = trim(a.replace(/http:\/\//i, "")); 12 } 13 return a; 14 }
将键值对拼接成URL带参数
1 export default const fnParams2Url = obj=> { 2 let aUrl = [] 3 let fnAdd = function(key, value) { 4 return key + '=' + value 5 } 6 for (var k in obj) { 7 aUrl.push(fnAdd(k, obj[k])) 8 } 9 return encodeURIComponent(aUrl.join('&')) 10 }
打开一个窗体通用方法
1 function openWindow(url, windowName, width, height) { 2 var x = parseInt(screen.width / 2.0) - width / 2.0; 3 var y = parseInt(screen.height / 2.0) - height / 2.0; 4 var isMSIE = navigator.appName == "Microsoft Internet Explorer"; 5 if (isMSIE) { 6 var p = "resizable=1,location=no,scrollbars=no,width="; 7 p = p + width; 8 p = p + ",height="; 9 p = p + height; 10 p = p + ",left="; 11 p = p + x; 12 p = p + ",top="; 13 p = p + y; 14 retval = window.open(url, windowName, p); 15 } else { 16 var win = window.open( 17 url, 18 "ZyiisPopup", 19 "top=" + 20 y + 21 ",left=" + 22 x + 23 ",scrollbars=" + 24 scrollbars + 25 ",dialog=yes,modal=yes,width=" + 26 width + 27 ",height=" + 28 height + 29 ",resizable=no" 30 ); 31 eval("try { win.resizeTo(width, height); } catch(e) { }"); 32 win.focus(); 33 } 34 }
解决offsetX兼容性问题
1 // 针对火狐不支持offsetX/Y 2 function getOffset(e) { 3 var target = e.target, // 当前触发的目标对象 4 eventCoord, 5 pageCoord, 6 offsetCoord; 7 8 // 计算当前触发元素到文档的距离 9 pageCoord = getPageCoord(target); 10 11 // 计算光标到文档的距离 12 eventCoord = { 13 X: window.pageXOffset + e.clientX, 14 Y: window.pageYOffset + e.clientY 15 }; 16 17 // 相减获取光标到第一个定位的父元素的坐标 18 offsetCoord = { 19 X: eventCoord.X - pageCoord.X, 20 Y: eventCoord.Y - pageCoord.Y 21 }; 22 return offsetCoord; 23 } 24 25 function getPageCoord(element) { 26 var coord = { X: 0, Y: 0 }; 27 // 计算从当前触发元素到根节点为止, 28 // 各级 offsetParent 元素的 offsetLeft 或 offsetTop 值之和 29 while (element) { 30 coord.X += element.offsetLeft; 31 coord.Y += element.offsetTop; 32 element = element.offsetParent; 33 } 34 return coord; 35 }
加载样式文件
1 function loadStyle(url) { 2 try { 3 document.createStyleSheet(url); 4 } catch (e) { 5 var cssLink = document.createElement("link"); 6 cssLink.rel = "stylesheet"; 7 cssLink.type = "text/css"; 8 cssLink.href = url; 9 var head = document.getElementsByTagName("head")[0]; 10 head.appendChild(cssLink); 11 } 12 }
判断是否打开视窗
1 function isViewportOpen() { 2 return !!document.getElementById("wixMobileViewport"); 3 }
判断是否为网址
1 function isURL(strUrl) { 2 var regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i; 3 if (regular.test(strUrl)) { 4 return true; 5 } else { 6 return false; 7 } 8 }
判断是否Touch屏幕
1 function isTouchScreen() { 2 return ( 3 "ontouchstart" in window || 4 (window.DocumentTouch && document instanceof DocumentTouch) 5 ); 6 }
判断鼠标是否移出事件
1 function isMouseOut(e, handler) { 2 if (e.type !== "mouseout") { 3 return false; 4 } 5 var reltg = e.relatedTarget 6 ? e.relatedTarget 7 : e.type === "mouseout" 8 ? e.toElement 9 : e.fromElement; 10 while (reltg && reltg !== handler) { 11 reltg = reltg.parentNode; 12 } 13 return reltg !== handler; 14 }
判断是否是移动设备访问
1 function isMobileUserAgent() { 2 return /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test( 3 window.navigator.userAgent.toLowerCase() 4 ); 5 }
判断吗是否手机号码
1 function isMobileNumber(e) { 2 var i = 3 "134,135,136,137,138,139,150,151,152,157,158,159,187,188,147,182,183,184,178", 4 n = "130,131,132,155,156,185,186,145,176", 5 a = "133,153,180,181,189,177,173,170", 6 o = e || "", 7 r = o.substring(0, 3), 8 d = o.substring(0, 4), 9 s = 10 !!/^1\d{10}$/.test(o) && 11 (n.indexOf(r) >= 0 12 ? "联通" 13 : a.indexOf(r) >= 0 14 ? "电信" 15 : "1349" == d 16 ? "电信" 17 : i.indexOf(r) >= 0 18 ? "移动" 19 : "未知"); 20 return s; 21 }
判断是否移动设备
1 function isMobile() { 2 if (typeof this._isMobile === "boolean") { 3 return this._isMobile; 4 } 5 var screenWidth = this.getScreenWidth(); 6 var fixViewPortsExperiment = 7 rendererModel.runningExperiments.FixViewport || 8 rendererModel.runningExperiments.fixviewport; 9 var fixViewPortsExperimentRunning = 10 fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new"; 11 if (!fixViewPortsExperiment) { 12 if (!this.isAppleMobileDevice()) { 13 screenWidth = screenWidth / window.devicePixelRatio; 14 } 15 } 16 var isMobileScreenSize = screenWidth < 600; 17 var isMobileUserAgent = false; 18 this._isMobile = isMobileScreenSize && this.isTouchScreen(); 19 return this._isMobile; 20 }
是否是某类手机型号
1 // 用devicePixelRatio和分辨率判断 2 const isIphonex = () => { 3 // X XS, XS Max, XR 4 const xSeriesConfig = [ 5 { 6 devicePixelRatio: 3, 7 width: 375, 8 height: 812 9 }, 10 { 11 devicePixelRatio: 3, 12 width: 414, 13 height: 896 14 }, 15 { 16 devicePixelRatio: 2, 17 width: 414, 18 height: 896 19 } 20 ]; 21 // h5 22 if (typeof window !== "undefined" && window) { 23 const isIOS = /iphone/gi.test(window.navigator.userAgent); 24 if (!isIOS) return false; 25 const { devicePixelRatio, screen } = window; 26 const { width, height } = screen; 27 return xSeriesConfig.some( 28 item => 29 item.devicePixelRatio === devicePixelRatio && 30 item.width === width && 31 item.height === height 32 ); 33 } 34 return false; 35 };
判断是否为数字类型
1 function isDigit(value) { 2 var patrn = /^[0-9]*$/; 3 if (patrn.exec(value) == null || value == "") { 4 return false; 5 } else { 6 return true; 7 } 8 }
判断是否苹果移动设备访问
1 function isAppleMobileDevice() { 2 return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()); 3 }
判断是否安卓移动设备访问
1 function isAndroidMobileDevice() { 2 return /android/i.test(navigator.userAgent.toLowerCase()); 3 }
获取移动设备最大化大小
1 function getZoom() { 2 var screenWidth = 3 Math.abs(window.orientation) === 90 4 ? Math.max(screen.height, screen.width) 5 : Math.min(screen.height, screen.width); 6 if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) { 7 screenWidth = screenWidth / window.devicePixelRatio; 8 } 9 var FixViewPortsExperiment = 10 rendererModel.runningExperiments.FixViewport || 11 rendererModel.runningExperiments.fixviewport; 12 var FixViewPortsExperimentRunning = 13 FixViewPortsExperiment && 14 (FixViewPortsExperiment === "New" || FixViewPortsExperiment === "new"); 15 if (FixViewPortsExperimentRunning) { 16 return screenWidth / window.innerWidth; 17 } else { 18 return screenWidth / document.body.offsetWidth; 19 } 20 }
获取窗体可见范围的宽与高
1 function getViewSize() { 2 var de = document.documentElement; 3 var db = document.body; 4 var viewW = de.clientWidth == 0 ? db.clientWidth : de.clientWidth; 5 var viewH = de.clientHeight == 0 ? db.clientHeight : de.clientHeight; 6 return Array(viewW, viewH); 7 }
检验URL链接是否有效
1 function getUrlState(URL) { 2 var xmlhttp = new ActiveXObject("microsoft.xmlhttp"); 3 xmlhttp.Open("GET", URL, false); 4 try { 5 xmlhttp.Send(); 6 } catch (e) { 7 } finally { 8 var result = xmlhttp.responseText; 9 if (result) { 10 if (xmlhttp.Status == 200) { 11 return true; 12 } else { 13 return false; 14 } 15 } else { 16 return false; 17 } 18 } 19 }
获取URL上的参数
1 // 获取URL中的某参数值,不区分大小写 2 // 获取URL中的某参数值,不区分大小写, 3 // 默认是取'hash'里的参数, 4 // 如果传其他参数支持取‘search’中的参数 5 // @param {String} name 参数名称 6 export function getUrlParam(name, type = "hash") { 7 let newName = name, 8 reg = new RegExp("(^|&)" + newName + "=([^&]*)(&|$)", "i"), 9 paramHash = window.location.hash.split("?")[1] || "", 10 paramSearch = window.location.search.split("?")[1] || "", 11 param; 12 13 type === "hash" ? (param = paramHash) : (param = paramSearch); 14 15 let result = param.match(reg); 16 17 if (result != null) { 18 return result[2].split("/")[0]; 19 } 20 return null; 21 }
获取网页被卷去的位置
1 function getScrollXY() { 2 return document.body.scrollTop 3 ? { 4 x: document.body.scrollLeft, 5 y: document.body.scrollTop 6 } 7 : { 8 x: document.documentElement.scrollLeft, 9 y: document.documentElement.scrollTop 10 }; 11 }
获取移动设备屏幕宽度
1 function getScreenWidth() { 2 var smallerSide = Math.min(screen.width, screen.height); 3 var fixViewPortsExperiment = 4 rendererModel.runningExperiments.FixViewport || 5 rendererModel.runningExperiments.fixviewport; 6 var fixViewPortsExperimentRunning = 7 fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new"; 8 if (fixViewPortsExperiment) { 9 if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) { 10 smallerSide = smallerSide / window.devicePixelRatio; 11 } 12 } 13 return smallerSide; 14 }
获取页面宽度
1 function getPageWidth() { 2 var g = document, 3 a = g.body, 4 f = g.documentElement, 5 d = g.compatMode == "BackCompat" ? a : g.documentElement; 6 return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth); 7 }
获取页面可视宽度
1 function getPageViewWidth() { 2 var d = document, 3 a = d.compatMode == "BackCompat" ? d.body : d.documentElement; 4 return a.clientWidth; 5 }
获取页面可视高度
1 function getPageViewHeight() { 2 var d = document, 3 a = d.compatMode == "BackCompat" ? d.body : d.documentElement; 4 return a.clientHeight; 5 }
获取页面高度
1 function getPageHeight() { 2 var g = document, 3 a = g.body, 4 f = g.documentElement, 5 d = g.compatMode == "BackCompat" ? a : g.documentElement; 6 return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight); 7 }
获取页面scrollLeft
1 function getPageScrollLeft() { 2 var a = document; 3 return a.documentElement.scrollLeft || a.body.scrollLeft; 4 }
获取页面scrollTop
1 function getPageScrollTop() { 2 var a = document; 3 return a.documentElement.scrollTop || a.body.scrollTop; 4 }
获取移动设备初始化大小
1 function getInitZoom() { 2 if (!this._initZoom) { 3 var screenWidth = Math.min(screen.height, screen.width); 4 if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) { 5 screenWidth = screenWidth / window.devicePixelRatio; 6 } 7 this._initZoom = screenWidth / document.body.offsetWidth; 8 } 9 return this._initZoom; 10 }
获得URL中GET参数值
1 // 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:GET["t1"], GET["t2"], GET["t3"] 2 function getGet() { 3 querystr = window.location.href.split("?"); 4 if (querystr[1]) { 5 GETs = querystr[1].split("&"); 6 GET = []; 7 for (i = 0; i < GETs.length; i++) { 8 tmp_arr = GETs.split("="); 9 key = tmp_arr[0]; 10 GET[key] = tmp_arr[1]; 11 } 12 } 13 return querystr[1]; 14 }
格式化CSS样式代码
1 function formatCss(s) { 2 //格式化代码 3 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); 4 s = s.replace(/;\s*;/g, ";"); //清除连续分号 5 s = s.replace(/\,[\s\.\#\d]*{/g, "{"); 6 s = s.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2"); 7 s = s.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2"); 8 s = s.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2"); 9 return s; 10 }
返回脚本内容
1 function evalscript(s) { 2 if (s.indexOf("<script") == -1) return s; 3 var p = /<script[^\>]*?>([^\x00]*?)<\/script>/gi; 4 var arr = []; 5 while ((arr = p.exec(s))) { 6 var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i; 7 var arr1 = []; 8 arr1 = p1.exec(arr[0]); 9 if (arr1) { 10 appendscript(arr1[1], "", arr1[2], arr1[3]); 11 } else { 12 p1 = /<script(.*?)>([^\x00]+?)<\/script>/i; 13 arr1 = p1.exec(arr[0]); 14 appendscript("", arr1[2], arr1[1].indexOf("reload=") != -1); 15 } 16 } 17 return s; 18 }
判断是否以某个字符串结束
1 String.prototype.endWith = function(s) { 2 var d = this.length - s.length; 3 return d >= 0 && this.lastIndexOf(s) == d; 4 };
跨浏览器删除事件
1 function delEvt(obj, evt, fn) { 2 if (!obj) { 3 return; 4 } 5 if (obj.addEventListener) { 6 obj.addEventListener(evt, fn, false); 7 } else if (oTarget.attachEvent) { 8 obj.attachEvent("on" + evt, fn); 9 } else { 10 obj["on" + evt] = fn; 11 } 12 }
时间日期格式转换
1 Date.prototype.format = function(formatStr) { 2 var str = formatStr; 3 var Week = ["日", "一", "二", "三", "四", "五", "六"]; 4 str = str.replace(/yyyy|YYYY/, this.getFullYear()); 5 str = str.replace( 6 /yy|YY/, 7 this.getYear() % 100 > 9 8 ? (this.getYear() % 100).toString() 9 : "0" + (this.getYear() % 100) 10 ); 11 str = str.replace( 12 /MM/, 13 this.getMonth() + 1 > 9 14 ? (this.getMonth() + 1).toString() 15 : "0" + (this.getMonth() + 1) 16 ); 17 str = str.replace(/M/g, this.getMonth() + 1); 18 str = str.replace(/w|W/g, Week[this.getDay()]); 19 str = str.replace( 20 /dd|DD/, 21 this.getDate() > 9 ? this.getDate().toString() : "0" + this.getDate() 22 ); 23 str = str.replace(/d|D/g, this.getDate()); 24 str = str.replace( 25 /hh|HH/, 26 this.getHours() > 9 ? this.getHours().toString() : "0" + this.getHours() 27 ); 28 str = str.replace(/h|H/g, this.getHours()); 29 str = str.replace( 30 /mm/, 31 this.getMinutes() > 9 32 ? this.getMinutes().toString() 33 : "0" + this.getMinutes() 34 ); 35 str = str.replace(/m/g, this.getMinutes()); 36 str = str.replace( 37 /ss|SS/, 38 this.getSeconds() > 9 39 ? this.getSeconds().toString() 40 : "0" + this.getSeconds() 41 ); 42 str = str.replace(/s|S/g, this.getSeconds()); 43 return str; 44 }; 45 46 // 或 47 Date.prototype.format = function(format) { 48 var o = { 49 "M+": this.getMonth() + 1, //month 50 "d+": this.getDate(), //day 51 "h+": this.getHours(), //hour 52 "m+": this.getMinutes(), //minute 53 "s+": this.getSeconds(), //second 54 "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 55 S: this.getMilliseconds() //millisecond 56 }; 57 if (/(y+)/.test(format)) 58 format = format.replace( 59 RegExp.$1, 60 (this.getFullYear() + "").substr(4 - RegExp.$1.length) 61 ); 62 for (var k in o) { 63 if (new RegExp("(" + k + ")").test(format)) 64 format = format.replace( 65 RegExp.$1, 66 RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length) 67 ); 68 } 69 return format; 70 }; 71 alert(new Date().format("yyyy-MM-dd hh:mm:ss"));
字符串长度截取
1 function cutstr(str, len) { 2 var temp, 3 icount = 0, 4 patrn = /[^\x00-\xff]/, 5 strre = ""; 6 for (var i = 0; i < str.length; i++) { 7 if (icount < len - 1) { 8 temp = str.substr(i, 1); 9 if (patrn.exec(temp) == null) { 10 icount = icount + 1 11 } else { 12 icount = icount + 2 13 } 14 strre += temp 15 } else { 16 break; 17 } 18 } 19 return strre + "..." 20 }
获取当前路径
1 var currentPageUrl = ""; 2 if (typeof this.href === "undefined") { 3 currentPageUrl = document.location.toString().toLowerCase(); 4 } else { 5 currentPageUrl = this.href.toString().toLowerCase(); 6 }
压缩CSS样式代码
1 function compressCss(s) { 2 //压缩代码 3 s = s.replace(/\/\*(.|\n)*?\*\//g, ""); //删除注释 4 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); 5 s = s.replace(/\,[\s\.\#\d]*\{/g, "{"); //容错处理 6 s = s.replace(/;\s*;/g, ";"); //清除连续分号 7 s = s.match(/^\s*(\S+(\s+\S+)*)\s*$/); //去掉首尾空白 8 return s == null ? "" : s[1]; 9 }
版本对比
function compareVersion(v1, v2) { v1 = v1.split("."); v2 = v2.split("."); var len = Math.max(v1.length, v2.length); while (v1.length < len) { v1.push("0"); } while (v2.length < len) { v2.push("0"); } for (var i = 0; i < len; i++) { var num1 = parseInt(v1[i]); var num2 = parseInt(v2[i]); if (num1 > num2) { return 1; } else if (num1 < num2) { return -1; } } return 0; }
全角半角转换
1 //iCase: 0全到半,1半到全,其他不转化 2 function chgCase(sStr, iCase) { 3 if ( 4 typeof sStr != "string" || 5 sStr.length <= 0 || 6 !(iCase === 0 || iCase == 1) 7 ) { 8 return sStr; 9 } 10 var i, 11 oRs = [], 12 iCode; 13 if (iCase) { 14 /*半->全*/ 15 for (i = 0; i < sStr.length; i += 1) { 16 iCode = sStr.charCodeAt(i); 17 if (iCode == 32) { 18 iCode = 12288; 19 } else if (iCode < 127) { 20 iCode += 65248; 21 } 22 oRs.push(String.fromCharCode(iCode)); 23 } 24 } else { 25 /*全->半*/ 26 for (i = 0; i < sStr.length; i += 1) { 27 iCode = sStr.charCodeAt(i); 28 if (iCode == 12288) { 29 iCode = 32; 30 } else if (iCode > 65280 && iCode < 65375) { 31 iCode -= 65248; 32 } 33 oRs.push(String.fromCharCode(iCode)); 34 } 35 } 36 return oRs.join(""); 37 }
确认是否是键盘有效输入值
1 function checkKey(iKey) { 2 if (iKey == 32 || iKey == 229) { 3 return true; 4 } /*空格和异常*/ 5 if (iKey > 47 && iKey < 58) { 6 return true; 7 } /*数字*/ 8 if (iKey > 64 && iKey < 91) { 9 return true; 10 } /*字母*/ 11 if (iKey > 95 && iKey < 108) { 12 return true; 13 } /*数字键盘1*/ 14 if (iKey > 108 && iKey < 112) { 15 return true; 16 } /*数字键盘2*/ 17 if (iKey > 185 && iKey < 193) { 18 return true; 19 } /*符号1*/ 20 if (iKey > 218 && iKey < 223) { 21 return true; 22 } /*符号2*/ 23 return false; 24 }
实现base64解码
1 function base64_decode(data) { 2 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 3 var o1, 4 o2, 5 o3, 6 h1, 7 h2, 8 h3, 9 h4, 10 bits, 11 i = 0, 12 ac = 0, 13 dec = "", 14 tmp_arr = []; 15 if (!data) { 16 return data; 17 } 18 data += ""; 19 do { 20 h1 = b64.indexOf(data.charAt(i++)); 21 h2 = b64.indexOf(data.charAt(i++)); 22 h3 = b64.indexOf(data.charAt(i++)); 23 h4 = b64.indexOf(data.charAt(i++)); 24 bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4; 25 o1 = (bits >> 16) & 0xff; 26 o2 = (bits >> 8) & 0xff; 27 o3 = bits & 0xff; 28 if (h3 == 64) { 29 tmp_arr[ac++] = String.fromCharCode(o1); 30 } else if (h4 == 64) { 31 tmp_arr[ac++] = String.fromCharCode(o1, o2); 32 } else { 33 tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); 34 } 35 } while (i < data.length); 36 dec = tmp_arr.join(""); 37 dec = utf8_decode(dec); 38 return dec; 39 }
返回顶部的通用方法
1 function backTop(btnId) { 2 var btn = document.getElementById(btnId); 3 var d = document.documentElement; 4 var b = document.body; 5 window.onscroll = set; 6 btn.style.display = "none"; 7 btn.onclick = function() { 8 btn.style.display = "none"; 9 window.onscroll = null; 10 this.timer = setInterval(function() { 11 d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1); 12 b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1); 13 if (d.scrollTop + b.scrollTop == 0) 14 clearInterval(btn.timer, (window.onscroll = set)); 15 }, 10); 16 }; 17 function set() { 18 btn.style.display = d.scrollTop + b.scrollTop > 100 ? "block" : "none"; 19 } 20 } 21 backTop("goTop");
动态加载脚本文件
1 function appendscript(src, text, reload, charset) { 2 var id = hash(src + text); 3 if (!reload && in_array(id, evalscripts)) return; 4 if (reload && $(id)) { 5 $(id).parentNode.removeChild($(id)); 6 } 7 8 evalscripts.push(id); 9 var scriptNode = document.createElement("script"); 10 scriptNode.type = "text/javascript"; 11 scriptNode.id = id; 12 scriptNode.charset = charset 13 ? charset 14 : BROWSER.firefox 15 ? document.characterSet 16 : document.charset; 17 try { 18 if (src) { 19 scriptNode.src = src; 20 scriptNode.onloadDone = false; 21 scriptNode.onload = function() { 22 scriptNode.onloadDone = true; 23 JSLOADED[src] = 1; 24 }; 25 scriptNode.onreadystatechange = function() { 26 if ( 27 (scriptNode.readyState == "loaded" || 28 scriptNode.readyState == "complete") && 29 !scriptNode.onloadDone 30 ) { 31 scriptNode.onloadDone = true; 32 JSLOADED[src] = 1; 33 } 34 }; 35 } else if (text) { 36 scriptNode.text = text; 37 } 38 document.getElementsByTagName("head")[0].appendChild(scriptNode); 39 } catch (e) {} 40 }
提取页面代码中所有网址
1 var aa = document.documentElement.outerHTML 2 .match( 3 /(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\] ]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\] ]+)/gi 4 ) 5 .join("\r\n") 6 .replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\) ]*$/gim, ""); 7 alert(aa);
加入收藏夹
1 function addFavorite(sURL, sTitle) { 2 try { 3 window.external.addFavorite(sURL, sTitle); 4 } catch (e) { 5 try { 6 window.sidebar.addPanel(sTitle, sURL, ""); 7 } catch (e) { 8 alert("加入收藏失败,请使用Ctrl+D进行添加"); 9 } 10 } 11 }
跨浏览器绑定事件
1 function addEventSamp(obj, evt, fn) { 2 if (!oTarget) { 3 return; 4 } 5 if (obj.addEventListener) { 6 obj.addEventListener(evt, fn, false); 7 } else if (obj.attachEvent) { 8 obj.attachEvent("on" + evt, fn); 9 } else { 10 oTarget["on" + sEvtType] = fn; 11 } 12 }
HTML标签转义
1 // HTML 标签转义 2 // @param {Array.<DOMString>} templateData 字符串类型的tokens 3 // @param {...} ..vals 表达式占位符的运算结果tokens 4 // 5 function SaferHTML(templateData) { 6 var s = templateData[0]; 7 for (var i = 1; i < arguments.length; i++) { 8 var arg = String(arguments[i]); 9 // Escape special characters in the substitution. 10 s += arg 11 .replace(/&/g, "&") 12 .replace(/</g, "<") 13 .replace(/>/g, ">"); 14 // Don't escape special characters in the template. 15 s += templateData[i]; 16 } 17 return s; 18 } 19 // 调用 20 var html = SaferHTML`<p>这是关于字符串模板的介绍</p>`;
转义html标签
1 function HtmlEncode(text) { 2 return text 3 .replace(/&/g, "&") 4 .replace(/\"/g, '"') 5 .replace(/</g, "<") 6 .replace(/>/g, ">"); 7 }
为元素添加trigger方法
1 Element.prototype.trigger = function(type, data) { 2 var event = document.createEvent("HTMLEvents"); 3 event.initEvent(type, true, true); 4 event.data = data || {}; 5 event.eventName = type; 6 event.target = this; 7 this.dispatchEvent(event); 8 return this; 9 }; 10 11 NodeList.prototype.trigger = function(event) { 12 []["forEach"].call(this, function(el) { 13 el["trigger"](event); 14 }); 15 return this; 16 };
为元素添加on方法
1 Element.prototype.on = Element.prototype.addEventListener; 2 3 NodeList.prototype.on = function (event, fn) {、 4 []['forEach'].call(this, function (el) { 5 el.on(event, fn); 6 }); 7 return this; 8 };

浙公网安备 33010602011771号