function functionname(){这里是要执行的代码}
当调用该函数时,会执行函数内的代码。
可以在某事件发生时直接调用函数(比如当用户点击按钮时),并且可由 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... }
替换全部
string.prototype.replacealfunction(ss{ returthis.replace(neregexp(sgm)s) }
清除空格
string.prototype.trifunction({ vareextraspac/^\s*(.*?)\s+$/; returthis.replace(reextraspace$) }
清除左空格/右空格
functioltrim(s)returs.replace/^(\s*| *)/)} functiortrim(s)returs.replace/(\s*| *)$/)}
判断是否以某个字符串开头
string.prototype.startwitfunctio(s{ returthis.indexof(s= }
判断是否以某个字符串结束
string.prototype.endwitfunctio(s{ vathis.lengts.length; retur(>&this.lastindexof(s=d) }
转义html标签
functiohtmlencode(text{ returtext.replace(/&/g'&').replace(/\/g'').replace(/') }
时间日期格式转换
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 }
判断是否为数字类型
functioisdigit(value{ vapatr/^[-]*$/; i(patrn.exec(value=nul|valu={ returfalse els{ returtrue } }
设置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; }
获取cookie值
functiogetcookie(name{ vaardocument.cookie.match(neregexp((^)nam=([^;]*)(;|$))); i(ar!nullreturunescape(arr[]); returnull }
加入收藏夹
functioaddfavorite(surlstitle{ tr{ window.external.addfavorite(surlstitle) catch(e{ tr{ window.sidebar.addpanel(stitlesurl) catch(e{ alert(加入收藏失败,请使用ctrl+d进行添加) } } }
设为首页
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') } }
加载样式文件
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) } }
返回脚本内容
functioevalscript(s{ if(s.indexof('([^\x]*?)/ig; vaar[]; while(arp.exec(s){ vap/]*?src=\([^\>]*?)\[^\>]*?(reload=\\)?(?:charset=\([\w\-]+?)\)?>/i; vaarr[]; arrp.exec(arr[]); if(arr{ appendscript(arr[]''arr[]arr[]); els{ p/([^\x]+?)/i; arrp.exec(arr[]); appendscript(''arr[]arr[].indexof('reload='!-); } } returs; }
清除脚本内容
functiostripscript(s{ returs.replace(/.*?/ig''); }
动态加载脚本文件
functioappendscript(srctextreloadcharset{ vaihash(srtext); if(!reloa&in_array(idevalscripts)return; if(reloa&$(id){ $(id).parentnode.removechild($(id)); } evalscripts.push(id); vascriptnoddocument.createelement(script); scriptnode.typtext/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{} }
返回按id检索的元素对象
functio$(id{ retur!inuldocument.getelementbyid(id); }
跨浏览器绑定事件
functioaddeventsamp(obj,evt,fn){ if(!otarget){return;} i(obj.addeventlistener{ obj.addeventlistener(evtfnfalse); }elsif(obj.attachevent){ obj.attachevent('on'+evt,fn); }else{ otarget[onsevttypefn; } }
跨浏览器删除事件
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; } }
为元素添加on方法
element.prototype.oelement.prototype.addeventlistener; nodelist.prototype.ofunctio(eventfn{、 []['foreach'].call(thisfunctio(el{ el.on(eventfn); }); returthis; };
为元素添加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; };
检验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); } } }
格式化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; }
压缩css样式代码
functiocompresscs(s{//压缩代码 s.replace(/\/\*(.|\n)*?\*\//g)//删除注释 s.replace(/\s*([\{\}\:\;\,])\s*/g$); s.replace(/\,[\s\.\#\d]*\{/g{)//容错处理 s.replace(/;\s*;/g;)//清除连续分号 s.match(/^\s*(\s+(\s+\s+)*)\s*$/)//去掉首尾空白 retur(=nulls[]; }
获取当前路径
vacurrentpageur; i(typeothis.hre==undefined{ currentpageurdocument.location.tostring().tolowercase(); }els{ currentpageurthis.href.tostring().tolowercase(); }
判断是否移动设备
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; }
判断是否移动设备访问
functioismobileuseragent(){ retur(/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.useragent.tolowercase())); }
判断是否苹果移动设备访问
functioisapplemobiledevice(){ retur(/iphone|ipod|ipad|macintosh/i.test(navigator.useragent.tolowercase())); }
判断是否安卓移动设备访问
functioisandroidmobiledevice(){ retur(/android/i.test(navigator.useragent.tolowercase())); }
判断是否touch屏幕
functioistouchscreen(){ retur(('ontouchstartiwindow|window.documenttouc&documeninstanceodocumenttouch); }
判断是否打开视窗
functioisviewportopen({ retur!!document.getelementbyid('wixmobileviewport'); }
获取移动设备初始化大小
functiogetinitzoom(){ if(!this._initzoom){ vascreenwidtmath.min(screen.heightscreen.width); if(this.isandroidmobiledevice(&!this.isnewchromeonandroid()){ screenwidtscreenwidth/window.devicepixelratio; } this._initzooscreenwidt/document.body.offsetwidth; } returthis._initzoom; }
获取移动设备最大化大小
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; } }
获取移动设备屏幕宽度
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; }
完美判断是否为网址
functioisurl(strurl{ varegula/^\b(((https?|ftp):\/\/)?[-a-z-]+(\.[-a-z-]+)*\.(?: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-_:\@&?=+,.!\/~%\$]*)?)$/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}
获取页面高度
functiogetpageheight(){ vadocumentg.bodyg.documentelementg.compatmod=backcompat a g.documentelement; returmath.max(f.scrollheighta.scrollheightd.clientheight); }
获取页面scrollleft
functiogetpagescrollleft(){ vadocument; retura.documentelement.scrolllef|a.body.scrollleft; }
获取页面可视宽度
functiogetpageviewwidth(){ vadocumentd.compatmod=backcompat d.body d.documentelement; retura.clientwidth; }
获取页面宽度
functiogetpagewidth(){ vadocumentg.bodyg.documentelementg.compatmod=backcompat a g.documentelement; returmath.max(f.scrollwidtha.scrollwidthd.clientwidth); }
获取页面scrolltop
functiogetpagescrolltop(){ vadocument; retura.documentelement.scrollto|a.body.scrolltop; }
获取页面可视高度
functiogetpageviewheight({ vadocumentd.compatmod=backcompat d.body d.documentelement; retura.clientheight; }
去掉url前缀
functioremoveurlprefix(a){ a=a.replace(/:/g,:).replace(/./g,.).replace(///g,/); while(trim(a).tolowercase().indexof(http://)==){ a=trim(a.replace(/http:\/\//i,)); } retura; }
随机数时间戳
functiouniqueid(){ vaa=math.random,b=parseint; returnumber(nedate()).tostring()+b(*a())+b(*a())+b(*a()); }
全角半角转换
//icase全到半,半到全,其他不转化 functiochgcase(sstr,icase){ if(typeosst!string|sstr.lengt全*/ for(i=i半*/ for(i=i&ike){returtrue;}/*数字*/ if(ikey>&ike){returtrue;}/*字母*/ if(ikey>&ike){returtrue;}/*数字键盘*/ if(ikey>&ike){returtrue;}/*数字键盘*/ if(ikey>&ike){returtrue;}/*符号*/ if(ikey>&ike){returtrue;}/*符号*/ returfalse; }
获取网页被卷去的位置
functiogetscrollxy({ returdocument.body.scrollto{ xdocument.body.scrollleft, ydocument.body.scrolltop }{ xdocument.documentelement.scrollleft, ydocument.documentelement.scrolltop } }
日期格式化函数+调用方法
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));
时间个性化输出功能
./* .、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; }
解决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; .}常用的正则表达式 .//正整数 ./^[-]*[-][-]*$/; .//负整数 ./^-[-]*[-][-]*$/; .//正浮点数 ./^(([-]+\.[-]*[-][-]*)|([-]*[-][-]*\.[-]+)|([-]*[-][-]*))$/; .//负浮点数 ./^(-(([-]+\.[-]*[-][-]*)|([-]*[-][-]*\.[-]+)|([-]*[-][-]*)))$/; .//浮点数 ./^(-?\d+)(\.\d+)?$/; .//email地址 ./^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/; .//url地址 ./^[a-za-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\s*)?$/; .或:^http:\/\/[a-za-z-]+\.[a-za-z-]+[\/=\?%\-&_~`@[\]\':+!]*([^\\])*.//年/月/日(年-月-日、年.月.日) ./^(|)\d\d[/.]([-]|[])[/.]([-]|[][-]|[])$/; .//匹配中文字符 ./[\ue-\ufa]/; .//匹配帐号是否合法(字母开头,允许-字节,允许字母数字下划线) ./^[a-za-z][a-za-z-_]{,}$/; .//匹配空白行的正则表达式 ./\n\s*\r/; .//匹配中国邮政编码 ./[-]\d{}(?!\d)/; .//匹配身份证 ./\d{}|\d{}/; .//匹配国内电话号码 ./(\d{}-|\d{}-)?(\d{}|\d{})?/; .//匹配ip地址 ./(([-]\d|[-]|[]?\d\d?)\.){}([-]\d|[-]|[]?\d\d?)/; .//匹配首尾空白字符的正则表达式 ./^\s*|\s*$/; .//匹配html标记的正则表达式 .(\s*?)[^>]*>.*?|.*/>; .//sq语句 .^(select|drop|delete|create|update|insert).*$ .//提取信息中的网络链接 .(h|h)(r|r)(e|e)(f|f**('|)?(\w|\\|\/|\.)+('|*|>)? .//提取信息中的邮件地址 .\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* .//提取信息中的图片链接 .(s|s)(r|r)(c|c**('|)?(\w|\\|\/|\.)+('|*|>)? .//提取信息中i地址 .(\d+)\.(\d+)\.(\d+)\.(\d+) .//取信息中的中国手机号码 .()**\d{} .//提取信息中的中国邮政编码 .[-]{}(\d+){} .//提取信息中的浮点数(即小数) .(-?\d*)\.?\d+ .//提取信息中的任何数字 .(-?\d*)(\.\d+)? .//电话区号 .^\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.displanone; btn.onclicfunction({ btn.style.displanone; 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?t=&t=&t=那么能取得:get[t]get[t]get[t] .functioget_get(){ querystwindow.location.href.split(?) if(querystr[]){ getquerystr[].split(&); ge[]; for(i=;i\]*$/igm,); alert(aa); 清除相同的数组 string.prototype.unique=function(){ vax=this.split(/[\r\n]+/); vay=''; for(vai=;i]+/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.numberthe\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({ 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){ vababcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz+/=; 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