32个可以直接拿来使用的js_第1页
32个可以直接拿来使用的js_第2页
32个可以直接拿来使用的js_第3页
32个可以直接拿来使用的js_第4页
32个可以直接拿来使用的js_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、原生JavaScript实现字符串长度截取functioncutstr(str,len){vartemp;varicount=0;varpatrn=/[^\x00-\xff]/;varstrre="";for(vari=0;i<str.length;i++){if(icount<len-1){temp=str.substr(i,1);if(patrn.exec(temp)==null){icount=icount+1}else{icount=icount+2}strre+=temp}else{break}}returnstrre+"..."}2、原生JavaScript获取域名主机functiongetHost(url){varhost="null";if(typeofurl=="undefined"||null==url){url=window.location.href;}varregex=/^\w+\:\/\/([^\/]*).*/;varmatch=url.match(regex);if(typeofmatch!="undefined"&&null!=match){host=match[1];}returnhost;}3、原生JavaScript清除空格Stotype.trim=function(){varreExtraSpace=/^\s*(.*?)\s+$/;returnthis.replace(reExtraSpace,"$1")}4、原生JavaScript替换全部Stotype.replaceAll=function(s1,s2){returnthis.replace(newRegExp(s1,"gm"),s2)}5、原生JavaScript转义html标签functionHtmlEncode(text){returntext.replace(/&/g,'&').replace(/\"/g,'"').replace(/</g,'<').replace(/>/g,'>')}6、原生JavaScript还原html标签functionHtmlDecode(text){returntext.replace(/&/g,'&').replace(/"/g,'\"').replace(/</g,'<').replace(/>/g,'>')}7、原生JavaScript时间日期格式转换Dtotype.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}8、原生JavaScript判断是否为数字类型functionisDigit(value){varpatrn=/^[0-9]*$/;if(patrn.exec(value)==null||value==""){returnfalse}else{returntrue}}9、原生JavaScript设置cookie值functionsetCookie(name,value,Hours){vard=newDate();varoffset=8;varutc=d.getTime()+(d.getTimezoneOffset()*60000);varnd=utc+(*offset);varexp=newDate(nd);exp.setTime(exp.getTime()+Hours*60*60*1000);document.cookie=name+"="+escape(value)+";path=/;expires="+exp.toGMTString()+";domain=360;"}10、原生JavaScript获取cookie值functiongetCookie(name){vararr=document.cookie.match(newRegExp("(^|)"+name+"=([^;]*)(;|$)"));if(arr!=null)returnunescape(arr[2]);returnnull}11、原生JavaScript加入收藏夹functionAddFavorite(sURL,sTitle){try{window.external.addFavorite(sURL,sTitle)}catch(e){try{window.sidebar.addPanel(sTitle,sURL,"")}catch(e){alert("加入收藏失败,请使用Ctrl+D进行添加")}}}12、原生JavaScript设为首页functionsetHomepage(){if(document.all){document.body.style.behavior='url(#default#homepage)';document.body.setHomePage('http://***')}elseif(window.sidebar){if(scape){try{netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")}catch(e){alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入about:config,然后将项signed.applets.codebase_principal_support值该为true")}}varprefs=Components.classes['@/preferences-service;1'].getService(Cerfaces.nsIPrefBranch);prefs.setCharPref('browser.startup.homepage','http://***')}}13、原生JavaScript判断IE6varua=navigator.userAgent.toLowerCase();varisIE6=ua.indexOf("msie6")>-1;if(isIE6){try{document.execCommand("BackgroundImageCache",false,true)}catch(e){}}14、原生JavaScript加载样式文件functionLoadStyle(url){try{document.createStyleSheet(url)}catch(e){varcssLink=document.createElement('link');cssLink.rel='stylesheet';cssLink.type='text/css';cssLink.href=url;varhead=document.getElementsByTagName('head')[0];head.appendChild(cssLink)}}15、原生JavaScript返回脚本内容functionevalscript(s){if(s.indexOf('<script')==-1)returns;varp=/<script[^\>]*?>([^\x00]*?)<\/script>/ig;vararr=[];while(arr=p.exec(s)){varp1=/<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;vararr1=[];arr1=p1.exec(arr[0]);if(arr1){appendscript(arr1[1],'',arr1[2],arr1[3]);}else{p1=/<script(.*?)>([^\x00]+?)<\/script>/i;arr1=p1.exec(arr[0]);appendscript('',arr1[2],arr1[1].indexOf('reload=')!=-1);}}returns;}16、原生JavaScript清除脚本内容functionstripscript(s){returns.replace(/<script.*?>.*?<\/script>/ig,'');}17、原生JavaScript动态加载脚本文件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){}}18、原生JavaScript返回按ID检索的元素对象function$(id){return!id?null:document.getElementById(id);}19、原生JavaScript返回浏览器版本内容functionbrowserVersion(types){varother=1;for(iintypes){varv=types[i]?types[i]:i;if(USERAGENT.indexOf(v)!=-1){varre=newRegExp(v+'(\\/|\\s)([\\d\\.]+)','ig');varmatches=re.exec(USERAGENT);varver=matches!=null?matches[2]:0;other=ver!==0&&v!='mozilla'?0:other;}else{varver=0;}eval('BROWSER.'+i+'=ver');}BROWSER.other=other;}20、原生JavaScript元素显示的通用方法function$(id){return!id?null:document.getElementById(id);}functiondisplay(id){varobj=$(id);if(obj.style.visibility){obj.style.visibility=obj.style.visibility=='visible'?'hidden':'visible';}else{obj.style.display=obj.style.display==''?'none':'';}}21、原生JavaScript中有insertBefore方法,可惜却没有insertAfter方法?用如下函数实现functioninsertAfter(newChild,refChild){varparElem=refChild.parentNode;if(parElem.lastChild==refChild){refChild.appendChild(newChild);}else{parElem.insertBefore(newChild,refChild.nextSibling);}}22、原生JavaScript中兼容浏览器绑定元素事件functionaddEventSamp(obj,evt,fn){if(obj.addEventListener){obj.addEventListener(evt,fn,false);}elseif(obj.attachEvent){obj.attachEvent('on'+evt,fn);}}23、原生JavaScript光标停在文字的后面,文本框获得焦点时调用functionfocusLast(){vare=event.srcElement;varr=e.createTextRange();r.moveStart('character',e.value.length);r.collapse(true);r.select();}24、原生JavaScript检验URL链接是否有效functiongetUrlState(URL){varxmlhttp=newActiveXObject("microsoft.xmlhttp");xmlhttp.Open("GET",URL,false);try{xmlhttp.Send();}catch(e){}finally{varresult=xmlhttp.responseText;if(result){if(xmlhttp.Status==200){return(true);}else{return(false);}}else{return(false);}}}25、原生JavaScript格式化CSS样式代码functionformatCss(s){//格式化代码s=s.replace(/\s*([\{\}\:\;\,])\s*/g,"$1");s=s.replace(/;\s*;/g,";");//清除连续分号s=s.replace(/\,[\s\.\#\d]*{/g,"{");s=s.replace(/([^\s])\{([^\s])/g,"$1{\n\t$2");s=s.replace(/([^\s])\}([^\n]*)/g,"$1\n}\n$2");s=s.replace(/([^\s]);([^\s\}])/g,"$1;\n\t$2");returns;}26、原生JavaScript压缩CSS样式代码functionyasuoCss(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*$/);//去掉首尾空白return(s==null)?"":s[1];}27、原生JavaScript获取当前路径varcurrentPageUrl="";if(typeofthis.href==="undefined"){currentPageUrl=document.location.toString().toLowerCase();}else{currentPageUrl=this.href.toString().toLowerCase();}28、原生JavaScriptIP转成整型function_ip2int(ip){varnum=0;ip=ip.split(".");num=Number(ip[0])*256*256*256+Number(ip[1])*256*256+Number(ip[2])*256+Number(ip[3]);num=num>>>0;returnnum;}29、原生JavaScript整型解析为IP地址function_int2iP(num){varstr;vartt=newArray();tt[0]=(num>>>24)>>>0;tt[1]=((num<<8)>>>24)>>>0;tt[2]=(num<<16)>>>24;tt[3]=(num<<24)>>>24;str=String(tt[0])+"."+String(tt[1])+"."+String(tt[2])+"."+String(tt[3]);returnstr;}30、原生JavaScript实现checkbox全选与全不选functioncheckAll(){varselectall=document.getElementById("selectall");varallbox=document.getEleme

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论