Home > Web Front-end > JS Tutorial > body text

Daily collection of common JavaScript functions and methods_javascript skills

WBOY
Release: 2016-05-16 15:26:19
Original
1648 people have browsed it

函数就是包裹在花括号中的代码块,前面使用了关键词 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
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template