Home Web Front-end JS Tutorial Daily collection of common JavaScript functions and methods_javascript skills

Daily collection of common JavaScript functions and methods_javascript skills

May 16, 2016 pm 03:26 PM

函数就是包裹在花括号中的代码块,前面使用了关键词 function:

function functionname()
{
这里是要执行的代码
}
Copy after login

当调用该函数时,会执行函数内的代码。

可以在某事件发生时直接调用函数(比如当用户点击按钮时),并且可由 JavaScript 在任何位置进行调用。

提示:JavaScript 对大小写敏感。关键词 function 必须是小写的,并且必须以与函数名称相同的大小写来调用函数。

字符串长度截取

functiocutstr(strlen{
 vatemp,
 icoun,
 patr/[^\x-\xff]/,
 strr"";
 fo(vastr.lengthi++{
 i(icounle{
 temstr.substr(i);
 i(patrn.exec(temp=null{
 icounicoun
 els{
 icounicoun
 }
 strr+temp
 els{
 break;
 }
 }
 returstrr"..."
 }
Copy after login

替换全部

String.prototype.replaceAlfunction(ss{
 returthis.replace(neRegExp(s"gm")s)
 }
Copy after login

清除空格

 String.prototype.trifunction({
 vareExtraSpac/^\s*(.*?)\s+$/;
 returthis.replace(reExtraSpace"$")
 }
Copy after login

清除左空格/右空格

 functioltrim(s)returs.replace/^(\s*| *)/"")}
 functiortrim(s)returs.replace/(\s*| *)$/"")}
Copy after login

判断是否以某个字符串开头

String.prototype.startWitfunctio(s{
 returthis.indexOf(s=
 }
Copy after login

判断是否以某个字符串结束

String.prototype.endWitfunctio(s{
 vathis.lengts.length;
 retur(>&this.lastIndexOf(s=d)
 }
Copy after login

转义html标签

functioHtmlEncode(text{
 returtext.replace(/&/g'&').replace(/\"/g'"').replace(/</g'<').replace(/>/g'>')
 }
Copy after login

时间日期格式转换

Date.prototype.Formafunction(formatStr{
 vastformatStr;
 vaWee['日''一''二''三''四''五''六'];
 ststr.replace(/yyyy|YYYY/this.getFullYear());
 ststr.replace(/yy|YY/(this.getYear((this.getYear().toString('(this.getYear());
 ststr.replace(/MM/(this.getMonth((this.getMonth().toString('(this.getMonth());
 ststr.replace(/M/g(this.getMonth());
 ststr.replace(/w|W/gWeek[this.getDay()]);
 ststr.replace(/dd|DD/this.getDate(this.getDate().toString('this.getDate());
 ststr.replace(/d|D/gthis.getDate());
 ststr.replace(/hh|HH/this.getHours(this.getHours().toString('this.getHours());
 ststr.replace(/h|H/gthis.getHours());
 ststr.replace(/mm/this.getMinutes(this.getMinutes().toString('this.getMinutes());
 ststr.replace(/m/gthis.getMinutes());
 ststr.replace(/ss|SS/this.getSeconds(this.getSeconds().toString('this.getSeconds());
 ststr.replace(/s|S/gthis.getSeconds());
 returstr
 }
Copy after login

判断是否为数字类型

functioisDigit(value{
 vapatr/^[-]*$/;
 i(patrn.exec(value=nul|valu=""{
 returfalse
 els{
 returtrue
 }
 }
Copy after login

设置cookie值

 functiosetCookie(namevalueHours{
 vaneDate();
 vaoffse;
 vautd.getTime((d.getTimezoneOffset();
 vanut(offset);
 vaexneDate(nd);
 exp.setTime(exp.getTime(Hour);
 document.cookinam"=escape(value";path=/;expires=exp.toGMTString(";domain=doc.com;"
 }
Copy after login

获取cookie值

functiogetCookie(name{
 vaardocument.cookie.match(neRegExp("(^)nam"=([^;]*)(;|$)"));
 i(ar!nullreturunescape(arr[]);
 returnull
 }
Copy after login

加入收藏夹

functioAddFavorite(sURLsTitle{
 tr{
 window.external.addFavorite(sURLsTitle)
 catch(e{
 tr{
 window.sidebar.addPanel(sTitlesURL"")
 catch(e{
 alert("加入收藏失败,请使用Ctrl+D进行添加")
 }
 }
 }
Copy after login

设为首页

functiosetHomepage({
 i(document.all{
 document.body.style.behavio'url(#default#homepage)';
 document.body.setHomePage('http://wcboy.com')
 elsi(window.sidebar{
 i(window.netscape{
 tr{
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
 catch(e{
 alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输about:config,然后将signed.applets.codebase_principal_suppor值该为true")
 }
 }
 vaprefComponents.classes['@mozilla.org/preferences-service;'].getService(Components.interfaces.nsIPrefBranch);
 prefs.setCharPref('browser.startup.homepage''http://wcboy.com')
 }
 }
Copy after login

加载样式文件

functioLoadStyle(url{
 tr{
 document.createStyleSheet(url)
 catch(e{
 vacssLindocument.createElement('link');
 cssLink.re'stylesheet';
 cssLink.typ'text/css';
 cssLink.hreurl;
 vaheadocument.getElementsByTagName('head')[];
 head.appendChild(cssLink)
 }
 }
Copy after login

返回脚本内容

functioevalscript(s{
 if(s.indexOf('<script'=-returs;
 va/<script[^\>]*&#63;>([^\x]*&#63;)<\/script>/ig;
 vaar[];
 while(arp.exec(s){
 vap/<script[^\>]*&#63;src=\"([^\>]*&#63;)\"[^\>]*&#63;(reload=\"\")&#63;(&#63;:charset=\"([\w\-]+&#63;)\")&#63;><\/script>/i;
 vaarr[];
 arrp.exec(arr[]);
 if(arr{
 appendscript(arr[]''arr[]arr[]);
 els{
 p/<script(.*&#63;)>([^\x]+&#63;)<\/script>/i;
 arrp.exec(arr[]);
 appendscript(''arr[]arr[].indexOf('reload='!-);
 }
 }
 returs;
 }
Copy after login

清除脚本内容

 functiostripscript(s{
 returs.replace(/<script.*&#63;>.*&#63;<\/script>/ig'');
 }
Copy after login

动态加载脚本文件

functioappendscript(srctextreloadcharset{
 vaihash(srtext);
 if(!reloa&in_array(idevalscripts)return;
 if(reloa&$(id){
 $(id).parentNode.removeChild($(id));
 }
 evalscripts.push(id);
 vascriptNoddocument.createElement("script");
 scriptNode.typ"text/javascript";
 scriptNode.iid;
 scriptNode.charsecharsecharse(BROWSER.firefodocument.characterSedocument.charset);
 tr{
 if(src{
 scriptNode.srsrc;
 scriptNode.onloadDonfalse;
 scriptNode.onloafunctio({
 scriptNode.onloadDontrue;
 JSLOADED[src;
 };
 scriptNode.onreadystatechangfunctio({
 if((scriptNode.readyStat='loaded|scriptNode.readyStat='complete'&!scriptNode.onloadDone{
 scriptNode.onloadDontrue;
 JSLOADED[src;
 }
 };
 elsif(text){
 scriptNode.textext;
 }
 document.getElementsByTagName('head')[].appendChild(scriptNode);
 catch(e{}
 }
Copy after login

返回按ID检索的元素对象

functio$(id{
 retur!inuldocument.getElementById(id);
 }
Copy after login

跨浏览器绑定事件

functioaddEventSamp(obj,evt,fn){
 if(!oTarget){return;}
 i(obj.addEventListener{
 obj.addEventListener(evtfnfalse);
 }elsif(obj.attachEvent){
 obj.attachEvent('on'+evt,fn);
 }else{
 oTarget["onsEvtTypefn;
 }
 }
Copy after login

跨浏览器删除事件

 functiodelEvt(obj,evt,fn){
 if(!obj){return;}
 if(obj.addEventListener){
 obj.addEventListener(evt,fn,false);
 }elsif(oTarget.attachEvent){
 obj.attachEvent("onevt,fn);
 }else{
 obj["onevtfn;
 }
 }
Copy after login

为元素添加on方法

Element.prototype.oElement.prototype.addEventListener;
 NodeList.prototype.ofunctio(eventfn{、
 []['forEach'].call(thisfunctio(el{
 el.on(eventfn);
 });
 returthis;
 };
Copy after login

为元素添加trigger方法

Element.prototype.triggefunctio(typedata{
 vaevendocument.createEvent('HTMLEvents');
 event.initEvent(typetruetrue);
 event.datdat|{};
 event.eventNamtype;
 event.targethis;
 this.dispatchEvent(event);
 returthis;
 };
 NodeList.prototype.triggefunctio(event{
 []['forEach'].call(thisfunctio(el{
 el['trigger'](event);
 });
 returthis;
 };
Copy after login

检验URL链接是否有效

functiogetUrlState(URL){
 vaxmlhttneActiveXObject("microsoft.xmlhttp");
 xmlhttp.Open("GET",URLfalse);
 try{
 xmlhttp.Send();
 }catch(e){
 }finally{
 varesulxmlhttp.responseText;
 if(result){
 if(xmlhttp.Status==){
 return(true);
 }else{
 return(false);
 }
 }else{
 return(false);
 }
 }
 }
Copy after login

格式化CSS样式代码

 .functioformatCss(s){//格式化代码
 s.replace(/\s*([\{\}\:\;\,])\s*/g"$");
 s.replace(/;\s*;/g";")//清除连续分号
 s.replace(/\,[\s\.\#\d]*{/g"{");
 s.replace(/([^\s])\{([^\s])/g"${\n\t$");
 s.replace(/([^\s])\}([^\n]*)/g"$\n}\n$");
 s.replace(/([^\s]);([^\s\}])/g"$;\n\t$");
 returs;
 }
Copy after login

压缩CSS样式代码

functiocompressCs(s{//压缩代码
 s.replace(/\/\*(.|\n)*&#63;\*\//g"")//删除注释
 s.replace(/\s*([\{\}\:\;\,])\s*/g"$");
 s.replace(/\,[\s\.\#\d]*\{/g"{")//容错处理
 s.replace(/;\s*;/g";")//清除连续分号
 s.match(/^\s*(\S+(\s+\S+)*)\s*$/)//去掉首尾空白
 retur(=null"s[];
 }
Copy after login

获取当前路径

vacurrentPageUr"";
 i(typeothis.hre=="undefined"{
 currentPageUrdocument.location.toString().toLowerCase();
 }els{
 currentPageUrthis.href.toString().toLowerCase();
 }
Copy after login

判断是否移动设备

functioisMobile(){
 i(typeothis._isMobil=='boolean'){
 returthis._isMobile;
 }
 vascreenWidtthis.getScreenWidth();
 vafixViewPortsExperimenrendererModel.runningExperiments.FixViewpor||rendererModel.runningExperiments.fixviewport;
 vafixViewPortsExperimentRunninfixViewPortsExperimen&(fixViewPortsExperiment.toLowerCase(=="new");
 if(!fixViewPortsExperiment){
 if(!this.isAppleMobileDevice()){
 screenWidtscreenWidth/window.devicePixelRatio;
 }
 }
 vaisMobileScreenSizscreenWidt;
 vaisMobileUserAgenfalse;
 this._isMobilisMobileScreenSiz&this.isTouchScreen();
 returthis._isMobile;
 }
Copy after login

判断是否移动设备访问

functioisMobileUserAgent(){
 retur(/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
 }
Copy after login

判断是否苹果移动设备访问

functioisAppleMobileDevice(){
 retur(/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()));
 }
Copy after login

判断是否安卓移动设备访问

 functioisAndroidMobileDevice(){
 retur(/android/i.test(navigator.userAgent.toLowerCase()));
 }
Copy after login

判断是否Touch屏幕

functioisTouchScreen(){
 retur(('ontouchstartiwindow|window.DocumentTouc&documeninstanceoDocumentTouch);
 }
Copy after login

判断是否打开视窗

functioisViewportOpen({
 retur!!document.getElementById('wixMobileViewport');
 }
Copy after login

获取移动设备初始化大小

functiogetInitZoom(){
 if(!this._initZoom){
 vascreenWidtMath.min(screen.heightscreen.width);
 if(this.isAndroidMobileDevice(&!this.isNewChromeOnAndroid()){
 screenWidtscreenWidth/window.devicePixelRatio;
 }
 this._initZooscreenWidt/document.body.offsetWidth;
 }
 returthis._initZoom;
 }
Copy after login

获取移动设备最大化大小

functiogetZoom(){
 vascreenWidt(Math.abs(window.orientation==Math.max(screen.heightscreen.widthMath.min(screen.heightscreen.width);
 if(this.isAndroidMobileDevice(&!this.isNewChromeOnAndroid()){
 screenWidtscreenWidth/window.devicePixelRatio;
 }
 vaFixViewPortsExperimenrendererModel.runningExperiments.FixViewpor|rendererModel.runningExperiments.fixviewport;
 vaFixViewPortsExperimentRunninFixViewPortsExperimen&(FixViewPortsExperimen=="New|FixViewPortsExperimen=="new");
 if(FixViewPortsExperimentRunning){
 returscreenWidtwindow.innerWidth;
 }else{
 returscreenWidtdocument.body.offsetWidth;
 }
 }
Copy after login

获取移动设备屏幕宽度

functiogetScreenWidth(){
 vasmallerSidMath.min(screen.widthscreen.height);
 vafixViewPortsExperimenrendererModel.runningExperiments.FixViewpor|rendererModel.runningExperiments.fixviewport;
 vafixViewPortsExperimentRunninfixViewPortsExperimen&(fixViewPortsExperiment.toLowerCase(=="new");
 if(fixViewPortsExperiment){
 if(this.isAndroidMobileDevice(&!this.isNewChromeOnAndroid()){
 smallerSidsmallerSide/window.devicePixelRatio;
 }
 }
 retursmallerSide;
 }
Copy after login

完美判断是否为网址

functioIsURL(strUrl{
 varegula/^\b(((https&#63;|ftp):\/\/)&#63;[-a-z-]+(\.[-a-z-]+)*\.(&#63;:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|(([-])|([-]\d)|(\d\d)|([-]\d)|\d))\b(\/[-a-z-_:\@&&#63;=+,.!\/~%\$]*)&#63;)$/i
 i(regular.test(strUrl){
 returtrue;
 }els{
 returfalse;
 }
 }
getElementsByClassName
 .functiogetElementsByClassName(name{
 vatagdocument.getElementsByTagName('*'|document.all;
 vael[];
 fo(vatags.lengthi++{
 i(tags.className{
 vactags.className.split(');
 fo(vacs.lengthj++{
 i(nam=cs[j]{
 els.push(tags);
 break
 }
 }
 }
 }
 returels
}
Copy after login

获取页面高度

functiogetPageHeight(){
 vadocumentg.bodyg.documentElementg.compatMod="BackCompat"
 a
 g.documentElement;
 returMath.max(f.scrollHeighta.scrollHeightd.clientHeight);
 }
Copy after login

获取页面scrollLeft

functiogetPageScrollLeft(){
 vadocument;
 retura.documentElement.scrollLef|a.body.scrollLeft;
 }
Copy after login

获取页面可视宽度

functiogetPageViewWidth(){
 vadocumentd.compatMod="BackCompat"
 d.body
 d.documentElement;
 retura.clientWidth;
 }
Copy after login

获取页面宽度

functiogetPageWidth(){
 vadocumentg.bodyg.documentElementg.compatMod="BackCompat"
 a
 g.documentElement;
 returMath.max(f.scrollWidtha.scrollWidthd.clientWidth);
 }
Copy after login

获取页面scrollTop

functiogetPageScrollTop(){
 vadocument;
 retura.documentElement.scrollTo|a.body.scrollTop;
 }
Copy after login

获取页面可视高度

functiogetPageViewHeight({
 vadocumentd.compatMod="BackCompat"
 d.body
 d.documentElement;
 retura.clientHeight;
 }
Copy after login

去掉url前缀

functioremoveUrlPrefix(a){
 a=a.replace(/:/g,":").replace(/./g,".").replace(///g,"/");
 while(trim(a).toLowerCase().indexOf("http://")==){
 a=trim(a.replace(/http:\/\//i,""));
 }
 retura;
 }
Copy after login

随机数时间戳

functiouniqueId(){
 vaa=Math.random,b=parseInt;
 returNumber(neDate()).toString()+b(*a())+b(*a())+b(*a());
 }
Copy after login

全角半角转换

//iCase全到半,半到全,其他不转化
 functiochgCase(sStr,iCase){
 if(typeosSt!"string|sStr.lengt<|!(iCas==|iCas=)){
 retursStr;
 }
 vai,oRs=[],iCode;
 if(iCase){/*半->全*/
 for(i=i<sStr.length;i+=){
 iCodsStr.charCodeAt(i);
 if(iCod=){
 iCod;
 }elsif(iCod){
 iCod+;
 }
 oRs.push(String.fromCharCode(iCode));
 }
 }else{/*全->半*/
 for(i=i<sStr.length;i+=){
 iCodsStr.charCodeAt(i);
 if(iCod=){
 iCod;
 }elsif(iCod&iCod){
 iCod-;
 }
 oRs.push(String.fromCharCode(iCode));
 }
 }
 returoRs.join("");
 }
Copy after login

确认是否键盘有效输入值

functiocheckKey(iKey){
 if(iKe=|iKe=){returtrue;}/*空格和异常*/
 if(iKey>&iKe){returtrue;}/*数字*/
 if(iKey>&iKe){returtrue;}/*字母*/
 if(iKey>&iKe){returtrue;}/*数字键盘*/
 if(iKey>&iKe){returtrue;}/*数字键盘*/
 if(iKey>&iKe){returtrue;}/*符号*/
 if(iKey>&iKe){returtrue;}/*符号*/
 returfalse;
 }
Copy after login

获取网页被卷去的位置

 functiogetScrollXY({
 returdocument.body.scrollTo{
 xdocument.body.scrollLeft,
 ydocument.body.scrollTop
 }{
 xdocument.documentElement.scrollLeft,
 ydocument.documentElement.scrollTop
 }
 }
Copy after login

日期格式化函数+调用方法

Date.prototype.formafunction(format){
 va{
 "M+this.getMonth()+//month
 "d+this.getDate()//day
 "h+this.getHours()//hour
 "m+this.getMinutes()//minute
 "s+this.getSeconds()//second
 "q+Math.floor((this.getMonth()+)/)//quarter
 "Sthis.getMilliseconds(//millisecond
 };
 if(/(y+)/.test(format)format=format.replace(RegExp.$,
 (this.getFullYear()+"").substr(RegExp.$.length));
 for(vaio){
 if(neRegExp("("+")").test(format))
 formaformat.replace(RegExp.$,RegExp.$.length==o[k:(""o[k]).substr((""o[k]).length));
 }
 returformat;
 }
 alert(neDate().format("yyyy-MM-dhh:mm:ss"));
Copy after login

时间个性化输出功能

./*
 .、s显示为“刚刚”
 .、>mi&min显示与当前时间差“XX分钟前”
 .、>mi&day显示与当前时间差“今XX:XX”
 .、>da&year显示日期“XX月XXXX:XX”
 .、>year显示具体日期“XXXX年XX月XXXX:XX”
 .*/
 .functiotimeFormat(time){
 vadatneDate(time),
 curDatneDate(),
 yeadate.getFullYear(),
 montdate.getMonth(,
 dadate.getDate(),
 houdate.getHours(),
 minutdate.getMinutes(),
 curYeacurDate.getFullYear(),
 curHoucurDate.getHours(),
 timeStr;
 if(yeacurYear){
 timeStyea+'年'mont+'月'da+''hou+':'minute;
 }else{
 vapastTimcurDatdate,
 pastpastTime/;
 if(pastcurHour){
 timeStmont+'月'da+''hou+':'minute;
 }elsif(past>){
 timeSt'今hou+':'minut+'分';
 }else{
 vapastcurDate.getMinutes(minute;
 if(past){
 timeStpast+'分钟前';
 }else{
 timeSt'刚刚';
 }
 }
 }
 returtimeStr;
 }
Copy after login

解决offsetX兼容性问题

 ./针对火狐不支持offsetX/Y
 .functiogetOffset(e){
 vatargee.target/当前触发的目标对象
 eventCoord,
 pageCoord,
 offsetCoord;
 /计算当前触发元素到文档的距离
 pageCoorgetPageCoord(target);
 /计算光标到文档的距离
 eventCoor{
 window.pageXOffsee.clientX,
 window.pageYOffsee.clientY
 };
 /相减获取光标到第一个定位的父元素的坐标
 offsetCoor{
 eventCoord.pageCoord.X,
 eventCoord.pageCoord.Y
 };
 returoffsetCoord;
 .}
 .functiogetPageCoord(element){
 vacoor};
 /计算从当前触发元素到根节点为止,
 /各offsetParen元素offsetLefoffsetTo值之和
 whil(element){
 coord.+element.offsetLeft;
 coord.+element.offsetTop;
 elemenelement.offsetParent;
 }
 returcoord;
 .}
常用的正则表达式
 .//正整数
 ./^[-]*[-][-]*$/;
 .//负整数
 ./^-[-]*[-][-]*$/;
 .//正浮点数
 ./^(([-]+\.[-]*[-][-]*)|([-]*[-][-]*\.[-]+)|([-]*[-][-]*))$/;
 .//负浮点数
 ./^(-(([-]+\.[-]*[-][-]*)|([-]*[-][-]*\.[-]+)|([-]*[-][-]*)))$/;
 .//浮点数
 ./^(-&#63;\d+)(\.\d+)&#63;$/;
 .//email地址
 ./^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
 .//url地址
 ./^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\&#63;\S*)&#63;$/;
 .或:^http:\/\/[A-Za-z-]+\.[A-Za-z-]+[\/=\&#63;%\-&_~`@[\]\':+!]*([^<>\"\"])*
.//年/月/日(年-月-日、年.月.日)
 ./^(|)\d\d[/.]([-]|[])[/.]([-]|[][-]|[])$/;
 .//匹配中文字符
 ./[\ue-\ufa]/;
 .//匹配帐号是否合法(字母开头,允许-字节,允许字母数字下划线)
 ./^[a-zA-Z][a-zA-Z-_]{,}$/;
 .//匹配空白行的正则表达式
 ./\n\s*\r/;
 .//匹配中国邮政编码
 ./[-]\d{}(&#63;!\d)/;
 .//匹配身份证
 ./\d{}|\d{}/;
 .//匹配国内电话号码
 ./(\d{}-|\d{}-)&#63;(\d{}|\d{})&#63;/;
 .//匹配IP地址
 ./(([-]\d|[-]|[]&#63;\d\d&#63;)\.){}([-]\d|[-]|[]&#63;\d\d&#63;)/;
 .//匹配首尾空白字符的正则表达式
 ./^\s*|\s*$/;
 .//匹配HTML标记的正则表达式
 .(\S*&#63;)[^>]*>.*&#63;|.*/>;
 .//sq语句
 .^(select|drop|delete|create|update|insert).*$
 .//提取信息中的网络链接
 .(h|H)(r|R)(e|E)(f|F**('|")&#63;(\w|\\|\/|\.)+('|"*|>)&#63;
 .//提取信息中的邮件地址
 .\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
 .//提取信息中的图片链接
 .(s|S)(r|R)(c|C**('|")&#63;(\w|\\|\/|\.)+('|"*|>)&#63;
 .//提取信息中I地址
 .(\d+)\.(\d+)\.(\d+)\.(\d+)
 .//取信息中的中国手机号码
 .()**\d{}
 .//提取信息中的中国邮政编码
 .[-]{}(\d+){}
 .//提取信息中的浮点数(即小数)
 .(-&#63;\d*)\.&#63;\d+
 .//提取信息中的任何数字
 .(-&#63;\d*)(\.\d+)&#63;
 .//电话区号
 .^\d{,}$
 .//腾Q号
 .^[-]*[-][-]*
.//帐号(字母开头,允-字节,允许字母数字下划线)
 .^[a-zA-Z][a-zA-Z-_]{,}
.//中文、英文、数字及下划线
 .^[\ue-\ufa_a-zA-Z-]+$
返回顶部的通用方法
 .functiobackTop(btnId{
 vabtdocument.getElementById(btnId);
 vadocument.documentElement;
 vadocument.body;
 window.onscrolset;
 btn.style.displa"none";
 btn.onclicfunction({
 btn.style.displa"none";
 window.onscrolnull;
 this.timesetInterval(function({
 d.scrollTo-Math.ceil((d.scrollTob.scrollTop.);
 b.scrollTo-Math.ceil((d.scrollTob.scrollTop.);
 i((d.scrollTob.scrollTop=clearInterval(btn.timerwindow.onscrolset);
 });
 };
 functioset({
 btn.style.displa(d.scrollTob.scrollTo'block'"none"
 }
 .};
 .backTop('goTop');
获得URL中GET参数值
 ./用法:如果地址test.htm&#63;t=&t=&t=那么能取得:GET["t"]GET["t"]GET["t"]
 .functioget_get(){
 querystwindow.location.href.split("&#63;")
 if(querystr[]){
 GETquerystr[].split("&");
 GE[];
 for(i=;i<GETs.length;i++){
 tmp_arGETs.split("=")
 key=tmp_arr[]
 GET[keytmp_arr[]
 }
 }
 returquerystr[];
 .}
打开一个窗体通用方法
 .functioopenWindow(url,windowName,width,height){
 vaparseInt(screen.widt.(widt.);
 vaparseInt(screen.heigh.(heigh.);
 vaisMSIE(navigator.appNam="MicrosofInterneExplorer");
 i(isMSIE{
 va"resizable=,location=no,scrollbars=no,width=";
 p+width;
 p+",height=";
 p+height;
 p+",left=";
 p+x;
 p+",top=";
 p+y;
 retvawindow.open(urlwindowNamep);
 els{
 vawiwindow.open(url"ZyiisPopup""top=",left=",scrollbars=scrollbar",dialog=yes,modal=yes,width=widt",height=heigh",resizable=no);
 eval("trwin.resizeTo(widthheight)catch(e}");
 win.focus();
 }
 .}
 
提取页面代码中所有网址

 vaadocument.documentElement.outerHTML.match(/(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\]+)/ig).join("\r\n").replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\]*$/igm,"");
 alert(aa);
 
清除相同的数组
 String.prototype.unique=function(){
 vax=this.split(/[\r\n]+/);
 vay='';
 for(vai=;i<x.length;i++){
 if(!neRegExp("^"+x.replace(/([^\w])/ig,"\\$")+"$","igm").test(y)){
 y+=x+"\r\n"
 }
 }
 retury
 };
 
按字母排序,对每行进行数组排序

 functioSetSort(){
 vatext=K.value.split(/[\r\n]/).sort().join("\r\n");//顺序
 vatest=K.value.split(/[\r\n]/).sort().reverse().join("\r\n");//反序
 K.value=K.value!=text&#63;text:test;
 }
 
字符串反序
 functioIsReverse(text){
 returtext.split('').reverse().join('');
 }
 
清除html代码中的脚本

 functioclear_script(){
 K.value=K.value.replace(/<script.*&#63;>[\s\S]*&#63;<\/script>|\s+on[a-zA-Z]{,}\s&#63;=\s&#63;"[\s\S]*&#63;"|\s+on[a-zA-Z]{,}\s&#63;=\s&#63;'[\s\S]*&#63;'|\s+on[a-zA-Z]{,}\s&#63;=[>]+/ig,"");
 }
 动态执行JavaScript脚本
 functiojavascript(){
 try{
 eval(K.value);
 }catch(e){
 alert(e.message);
 }
 }
 
动态执行VBScript脚本

 functiovbscript(){
 try{
 vascript=document.getElementById("K").value;
 if(script.trim()=="")return;
 window.execScript('OErroResumNex\n'+script+'\IErr.Number<>The\MsgBo"请输入正确的VBScript脚本!",,"脚本错误!\EnIf',"vbscript")
 }catch(e){
 alert(e.message);
 }
 }
 
金额大写转换函数

 functiotransform(tranvalue{
 tr{
 va;
 vadneArray("""万""亿")//大单位
 vadneArray("拾""佰""仟")//小单位
 vadneArray("零""壹""贰""叁""肆""伍""陆""柒""捌""玖")//整数部分用
 //以下是小写转换成大写显示在合计大写的文本框
//分离整数与小数
 vasourcsplits(tranvalue);
 vanusource[];
 vadisource[];
 //转换整数部分
 va//计小单位
 va//计大单位
 vasu;
 vast"";
 valesource[].length//整数的长度
 fo(<leni++{
 vasource[].charAt(lei)//取得某个位数上的数字
 vab;
 i(l>{
 bsource[].charAt(le)//取得某个位数前一位上的数字
 }
 susuNumber(n);
 i(su!{
 stdw[Number(n)].concat(str)//取得该数字对应的大写数字,并插入到str字符串的前面
 i(=''su;
 }
 i(l>//在数字范围内
 i(!//加小单位
 i(b!{
 stdw[k].concat(str);
 }
 k++;
 els//不加小单位,加大单位
 ;
 vatemstr.charAt();
 i(tem="万|tem="亿"//若大单位前没有数字则舍去大单位
 ststr.substr(str.lengt);
 stdw[k].concat(str);
 su;
 }
 }
 i(=)//小单位到千则大单位进一
 k++;
 }
 }
 //转换小数部分
 vastrdi"";
 i(di!""{
 vadig.charAt();
 i(!{
 strdi+dw[Number(n)"角"//加数字
 }
 vadig.charAt();
 i(!{
 strdi+dw[Number(n)"分"//加数字
 }
 }
 st+"元strdig;
 catch(e{
 retur"元";
 }
 returstr;
}
//拆分整数与小数
functiosplits(tranvalue{
 vavaluneArray('''');
 temtranvalue.split(".");
 fo(vatemp.lengthi++{
 valutemp;
 }
 returvalue;
}
 
resize的操作

 (function(){
 vaffunction(){
 vadocument.documentElemendocument.documentElement.clientWidtdocument.body.clientWidth
 ,
 ,Element.extend(document.body)
 ,classnamb.className;
 if(r){
 //当窗体的宽度小于的时候执行相应的操作
 }else{
 //当窗体的宽度大于的时候执行相应的操作
 }
 }
 if(window.addEventListener){
 window.addEventListener('resize'function()fn()});
 }elsif(window.attachEvent){
 window.attachEvent('onresize'function()fn()});
 }
 fn();
 })();
 
实现base64解码

 functiobase_decode(data){
 vab"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/=";
 vaooohhhhbits,a,de"",tmp_ar[];
 i(!datareturdata}
 dat+'';
 d{
 hb.indexOf(data.charAt(i++));
 hb.indexOf(data.charAt(i++));
 hb.indexOf(data.charAt(i++));
 hb.indexOf(data.charAt(i++));
 bith<h<h<h;
 obit>xff;
 obit>xff;
 obitxff;
 i(h={
 tmp_arr[ac++String.fromCharCode(o);
 elsi(h={
 tmp_arr[ac++String.fromCharCode(oo);
 els{
 tmp_arr[ac++String.fromCharCode(ooo);
 }
 whil(data.length);
 detmp_arr.join('');
 deutf_decode(dec);
 returdec;
 }
 
实现utf8解码

 .functioutf_decode(str_data){
 vatmp_ar[],,a,,,;str_dat+'';
 whil(str_data.length{
 str_data.charCodeAt(i);
 i({
 tmp_arr[ac++String.fromCharCode(c);
 i++;
 elsi&{
 str_data.charCodeAt();
 tmp_arr[ac++String.fromCharCode(((<());
 +;
 els{
 str_data.charCodeAt();
 str_data.charCodeAt();
 tmp_arr[ac++String.fromCharCode(((<((<());
 +;
 }
 }
 returtmp_arr.join('');
 }
 
获取窗体可见范围的宽与高

 .functiogetViewSize(){
 vade=document.documentElement;
 vadb=document.body;
 vaviewW=de.clientWidth==db.clientWidtde.clientWidth;
 vaviewH=de.clientHeight==db.clientHeighde.clientHeight;
 returArray(view,viewH);
 }
 
断鼠标是否移出事件

 functioisMouseOut(ehandler{
 i(e.typ!='mouseout'{
 returfalse;
 }
 varelte.relatedTargee.relatedTargee.typ=='mouseoute.toElemene.fromElement;
 whil(relt&relt!=handler{
 reltreltg.parentNode;
 }
 retur(relt!=handler);
 }
 
半角转换为全角函数

 .functioToDBC(str){
 varesul'';
 for(vai=str.lengthi++){
 codstr.charCodeAt(i);
 if(cod>&cod<){
 resul+String.fromCharCode(str.charCodeAt(i);
 }elsi(cod=){
 resul+String.fromCharCode(str.charCodeAt(i);
 }else{
 resul+str.charAt(i);
 }
 }
 returresult;
 }
 
全角转换为半角函数
 .functioToCDB(str){
 varesul'';
 for(vai=str.lengthi++){
 codstr.charCodeAt(i);
 if(cod&cod<){
 resul+String.fromCharCode(str.charCodeAt(i);
 }elsi(cod=){
 resul+String.fromCharCode(str.charCodeAt();
 }else{
 resul+str.charAt(i);
 }
 }
 returresult;
 }
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles