JavaScript常用工具函数大全
本文实例总结了JavaScript常用工具函数。分享给大家供大家参考,具体如下:
为元素添加on方法
Element.prototype.on=Element.prototype.addEventListener; NodeList.prototype.on=function(event,fn){、 []['forEach'].call(this,function(el){ el.on(event,fn); }); returnthis; };
为元素添加trigger方法
Element.prototype.trigger=function(type,data){ varevent=document.createEvent("HTMLEvents"); event.initEvent(type,true,true); event.data=data||{}; event.eventName=type; event.target=this; this.dispatchEvent(event); returnthis; }; NodeList.prototype.trigger=function(event){ []["forEach"].call(this,function(el){ el["trigger"](event); }); returnthis; };
转义html标签
functionHtmlEncode(text){ returntext .replace(/&/g,"&") .replace(/\"/g,'"') .replace(//g,">"); }
HTML标签转义
//HTML标签转义 //@param{Array.}templateData字符串类型的tokens //@param{...}..vals表达式占位符的运算结果tokens // functionSaferHTML(templateData){ vars=templateData[0]; for(vari=1;i /g,">"); //Don'tescapespecialcharactersinthetemplate. s+=templateData[i]; } returns; } //调用 varhtml=SaferHTML` 这是关于字符串模板的介绍
`;
跨浏览器绑定事件
functionaddEventSamp(obj,evt,fn){ if(!oTarget){ return; } if(obj.addEventListener){ obj.addEventListener(evt,fn,false); }elseif(obj.attachEvent){ obj.attachEvent("on"+evt,fn); }else{ oTarget["on"+sEvtType]=fn; } }
加入收藏夹
functionaddFavorite(sURL,sTitle){ try{ window.external.addFavorite(sURL,sTitle); }catch(e){ try{ window.sidebar.addPanel(sTitle,sURL,""); }catch(e){ alert("加入收藏失败,请使用Ctrl+D进行添加"); } } }
提取页面代码中所有网址
varaa=document.documentElement.outerHTML .match( /(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\]]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\]]+)/gi ) .join("\r\n") .replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\)]*$/gim,""); alert(aa);
动态加载脚本文件
functionappendscript(src,text,reload,charset){ varid=hash(src+text); if(!reload&&in_array(id,evalscripts))return; if(reload&&$(id)){ $(id).parentNode.removeChild($(id)); } evalscripts.push(id); varscriptNode=document.createElement("script"); scriptNode.type="text/javascript"; scriptNode.id=id; scriptNode.charset=charset ?charset :BROWSER.firefox ?document.characterSet :document.charset; try{ if(src){ scriptNode.src=src; scriptNode.onloadDone=false; scriptNode.onload=function(){ scriptNode.onloadDone=true; JSLOADED[src]=1; }; scriptNode.onreadystatechange=function(){ if( (scriptNode.readyState=="loaded"|| scriptNode.readyState=="complete")&& !scriptNode.onloadDone ){ scriptNode.onloadDone=true; JSLOADED[src]=1; } }; }elseif(text){ scriptNode.text=text; } document.getElementsByTagName("head")[0].appendChild(scriptNode); }catch(e){} }
返回顶部的通用方法
functionbackTop(btnId){ varbtn=document.getElementById(btnId); vard=document.documentElement; varb=document.body; window.onscroll=set; btn.style.display="none"; btn.onclick=function(){ btn.style.display="none"; window.onscroll=null; this.timer=setInterval(function(){ d.scrollTop-=Math.ceil((d.scrollTop+b.scrollTop)*0.1); b.scrollTop-=Math.ceil((d.scrollTop+b.scrollTop)*0.1); if(d.scrollTop+b.scrollTop==0) clearInterval(btn.timer,(window.onscroll=set)); },10); }; functionset(){ btn.style.display=d.scrollTop+b.scrollTop>100?"block":"none"; } } backTop("goTop");
实现base64解码
functionbase64_decode(data){ varb64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; varo1, o2, o3, h1, h2, h3, h4, bits, i=0, ac=0, dec="", tmp_arr=[]; if(!data){ returndata; } data+=""; do{ h1=b64.indexOf(data.charAt(i++)); h2=b64.indexOf(data.charAt(i++)); h3=b64.indexOf(data.charAt(i++)); h4=b64.indexOf(data.charAt(i++)); bits=(h1<<18)|(h2<<12)|(h3<<6)|h4; o1=(bits>>16)&0xff; o2=(bits>>8)&0xff; o3=bits&0xff; if(h3==64){ tmp_arr[ac++]=String.fromCharCode(o1); }elseif(h4==64){ tmp_arr[ac++]=String.fromCharCode(o1,o2); }else{ tmp_arr[ac++]=String.fromCharCode(o1,o2,o3); } }while(i确认是否是键盘有效输入值
functioncheckKey(iKey){ if(iKey==32||iKey==229){ returntrue; }/*空格和异常*/ if(iKey>47&&iKey<58){ returntrue; }/*数字*/ if(iKey>64&&iKey<91){ returntrue; }/*字母*/ if(iKey>95&&iKey<108){ returntrue; }/*数字键盘1*/ if(iKey>108&&iKey<112){ returntrue; }/*数字键盘2*/ if(iKey>185&&iKey<193){ returntrue; }/*符号1*/ if(iKey>218&&iKey<223){ returntrue; }/*符号2*/ returnfalse; }全角半角转换
//iCase:0全到半,1半到全,其他不转化 functionchgCase(sStr,iCase){ if( typeofsStr!="string"|| sStr.length<=0|| !(iCase===0||iCase==1) ){ returnsStr; } vari, oRs=[], iCode; if(iCase){ /*半->全*/ for(i=0;i半*/ for(i=0;i 65280&&iCode<65375){ iCode-=65248; } oRs.push(String.fromCharCode(iCode)); } } returnoRs.join(""); } 版本对比
functioncompareVersion(v1,v2){ v1=v1.split("."); v2=v2.split("."); varlen=Math.max(v1.length,v2.length); while(v1.lengthnum2){ return1; }elseif(num1 压缩CSS样式代码
functioncompressCss(s){ //压缩代码 s=s.replace(/\/\*(.|\n)*?\*\//g,"");//删除注释 s=s.replace(/\s*([\{\}\:\;\,])\s*/g,"$1"); s=s.replace(/\,[\s\.\#\d]*\{/g,"{");//容错处理 s=s.replace(/;\s*;/g,";");//清除连续分号 s=s.match(/^\s*(\S+(\s+\S+)*)\s*$/);//去掉首尾空白 returns==null?"":s[1]; }获取当前路径
varcurrentPageUrl=""; if(typeofthis.href==="undefined"){ currentPageUrl=document.location.toString().toLowerCase(); }else{ currentPageUrl=this.href.toString().toLowerCase(); }字符串长度截取
functioncutstr(str,len){ vartemp, icount=0, patrn=/[^\x00-\xff]/, strre=""; for(vari=0;i时间日期格式转换
Date.prototype.format=function(formatStr){ varstr=formatStr; varWeek=["日","一","二","三","四","五","六"]; str=str.replace(/yyyy|YYYY/,this.getFullYear()); str=str.replace( /yy|YY/, this.getYear()%100>9 ?(this.getYear()%100).toString() :"0"+(this.getYear()%100) ); str=str.replace( /MM/, this.getMonth()+1>9 ?(this.getMonth()+1).toString() :"0"+(this.getMonth()+1) ); str=str.replace(/M/g,this.getMonth()+1); str=str.replace(/w|W/g,Week[this.getDay()]); str=str.replace( /dd|DD/, this.getDate()>9?this.getDate().toString():"0"+this.getDate() ); str=str.replace(/d|D/g,this.getDate()); str=str.replace( /hh|HH/, this.getHours()>9?this.getHours().toString():"0"+this.getHours() ); str=str.replace(/h|H/g,this.getHours()); str=str.replace( /mm/, this.getMinutes()>9 ?this.getMinutes().toString() :"0"+this.getMinutes() ); str=str.replace(/m/g,this.getMinutes()); str=str.replace( /ss|SS/, this.getSeconds()>9 ?this.getSeconds().toString() :"0"+this.getSeconds() ); str=str.replace(/s|S/g,this.getSeconds()); returnstr; }; //或 Date.prototype.format=function(format){ varo={ "M+":this.getMonth()+1,//month "d+":this.getDate(),//day "h+":this.getHours(),//hour "m+":this.getMinutes(),//minute "s+":this.getSeconds(),//second "q+":Math.floor((this.getMonth()+3)/3),//quarter S:this.getMilliseconds()//millisecond }; if(/(y+)/.test(format)) format=format.replace( RegExp.$1, (this.getFullYear()+"").substr(4-RegExp.$1.length) ); for(varkino){ if(newRegExp("("+k+")").test(format)) format=format.replace( RegExp.$1, RegExp.$1.length==1?o[k]:("00"+o[k]).substr((""+o[k]).length) ); } returnformat; }; alert(newDate().format("yyyy-MM-ddhh:mm:ss"));跨浏览器删除事件
functiondelEvt(obj,evt,fn){ if(!obj){ return; } if(obj.addEventListener){ obj.addEventListener(evt,fn,false); }elseif(oTarget.attachEvent){ obj.attachEvent("on"+evt,fn); }else{ obj["on"+evt]=fn; } }判断是否以某个字符串结束
String.prototype.endWith=function(s){ vard=this.length-s.length; returnd>=0&&this.lastIndexOf(s)==d; };返回脚本内容
functionevalscript(s){ if(s.indexOf("