计算机200多个js技巧代码梳理汇总.docx
200多个js技巧代码1 .文本框焦点问题OnBIUr:当失去输入焦点后产生该事件OnFoCUs:当输入获得焦点后,产生该文件OnChange:当文字值改变时,产生该事件OnSeIeCI:当文字加亮后,产生该文件<inputtype="1.ext"VaIUe="mm"onfocus=if(va1.ue="mm)va1.ue=''"onb1.ur=*if(VaIUe='')va1.ue='三f”点击时文字消失,失去焦点时文字再出现2 .网页按钮的特殊颜色<inputtype=buttonname=*Submi11"YaIUe="郭强"size=10CIaSS=S02Sty1.e="background-co1.or:rgb(235,207,22)”>3 .鼠标移入移出时颜色变化<inputtype="submit"Va1.Ue="找吧"name=*B1.*OnVoUSeoUt=this,sty1.e.Co1.Or="b1.ue"OnVOUSeOVer=this.sty1.e.Co1.or="red"C1.aSS="button”)<SE1.ECT><FORM><BODY><HTM1.>17,将按钮的特征改变<sty1.etype=z,textcss*><!.Sty1.e1.font-size:12px;background:#CCCCFF;border-width:thinthinthinthin;border-co1.or:ffCCCCFFKCCCCCffCCCCCC#CCCCFF).sty1.e2font-size:12px;font-weight:bo1.d:background:SCCFFCC;border-width:thinmediummediumthin:border-co1.or:#CCFF99#999999#999999#CCFF99><sty1.e>本例按钮的代码如下:<inputtype=*submit,name="Submit"Va1.Ue="提交"OnmOUSeoVer="this.cIassName=*S1.yIe2'"OnmOUSeou1.="Ihis.cIassName='sty1.e”CIaSS="s1.y1.e1.”18 .改变按钮的图片.<sty1.etype="textcss”><!.sty1.e3font-size:12px;background:ur1.(image/buttonbg1.gif);border:Opx;width:60px;height:22px.sty1.e4font-size:12px;font-weight:bo1.d:background:ur1.(imagebuttonbg2.gif);bo1.der:Opx0;width:60px;height:22px><sty1.e>本例的按钮代码如下:<inputtype="submit"name="Submi1.2"Va1.Ue="提交"onmouseover=*this.C1.assName=*sty1.e4,”OnmoUSeOUt="this.C1.assName='sty1.e3,“CIaSS="sty1.e3”>19 .打印页面<diVa1.ign="center"><aCIaSS=ConIenIhref="javascriptRoPrint()>”>打印本稿<aXdiv>20 .可以直接写htm1.语言document,wriIe("");21 .改变下拉框的颜色<se1.ectname="c1.assid”onChange=,changeIocation(document,myform,c1.assic!,optionsdocment.myform,c1.assid.Se1.ectedIndex.va1.ue)”SiZe=Tsty1.e=*co1.or:tt008080;font-size:9pt*>22 .转至目标UR1.window.Iocation=*httpguoguo*23 .传递该object的formUpdateSN(,guoqiang99267',this,form)functionUpdateSN(strVa1.e,StrForm)StrForm.SignInName.va1.ue=StrVa1.ue:returnfa1.se:24 .文字标签<1.abe1.for=z,A1.tName4*><inputname="A1.1.Name"type="RADI()”tabindex=*931,id="A1.tName4”>guoqiang99859<1.abe1>25 .Iayer2为组件的ID,可以控制组件是否可见document,a1.1.item('1.ayer2').sty1.e,disp1.ay="b1.ock”;document,a1.1.item(,1.ayer2,).sty1.e,disp1.ay="none"26 .将页面加入favorite中<script1anguage=javascript><!functionAddmeOur1.="htp:your.site.address"/你自己的主页地址tit1.e="YourSiteName*;/你自己的主页名称window,externa1.AddFavorite(ur1.,tit1.e);><script>/27 .过10秒自动关闭页面< scriptIangUage="JavaScript.”>functionc1.oseitOSetTimeout(*se1.f.c1.ose()”,10000)< /script>28 .可以比较字符的大小char=post.charAt(i);if(!(,O><=char&&char<=,9')29 .将字符转化为数字month=parseInt(char)30 .点击VaIUe非空的选项时转向指定连接<se1.ectonchange='i(this,va1.ue!="")window,open(this,va1.ue)C1.aSS="textinput”<optionSeIeCi.ed>主办单位</。P1.iOn<option><option><optionva1.ue=*.Cn/”>北京日报<oPtiC)n><optionVaIUe="http:WW”>北京晚报/option)<se1.ect>31 .改变背景颜色<tdwidth=*c1.ass=dpbgCo1.or=#FAFBFCOnmOUSeoVer="this.bgCo1.or='ttFFFFFF,OnmOUSeQUt="Ihis.bgCo1.or='UFFBFC'32 .改变文字输入框的背景颜色<sty1.e>.input2background-image:ur1.(,./images/inputbg.gif');font-size:12px;background-co1.or:ffDODBB:border-top-width:Ipx;border-right-width:Ipx;boi'der-bo11om-width:1.px;bordei1.eft-width:1.px<sty1.e><inputname=contenttype=textSiZe="47"C1.aSS="input2”max1.ength=-50*>33 .改变水平线的特征<hrSiZe="O"noshadeco1.or="#CoCOCO”>34 .传递参数的方式<ahref="vote.asp?CurPage=8&id=3488w>8<a>35 .页内跳转< ahref=>1.<a>< ahref=Y2">2<a>< ahref=T3">3<a>< ahref=*4*>4<a>< ahref=5">5<a>< ahref=飞6">6<a>< ahref=*#7*>7</a><aname="1.">dfdf<a>< aname="2">dfdf</a>36 .两个按键一起按下if(event.Ctr1.Key&&window,event.keyCode=13)/37 .刷新页面javascript:this,1.ocation,re1.oad()/38 .将网页的按钮使能<SCRI1.ANGUAGE=*JavaScript*>functionhaha()for(vari=0;i<document.form1.e1.ements,1.ength;i+)if(document,fo11n1.e1.ementsi.name,indexf("bb")!=-1.)document,form1.e1.ementsi.disab1ed=!document.form1.e1.ementsi.disab1.ed;)<SCRIPT><B0DY><formname=form1.><INPUTTYPE="button"NAME=*aa"va1.ue=cindyonc1.ick=haha()><INPUTTYPE="button"NAME="bb"va1.ue=guoguo><INPUTTYPE="button"NAME=*bb"va1.ue=guoguo>39 .文字移动<marqueescro1.Iamount=3onmouseover=this.stopO;onnouseout=this.start();>40 .双击网页自动跑<SCRI1.ANGUAGE=*JavaScript*>Varcurrentpos,timer;functioninitia1.ize()timer=SetInterVa1("SCrO1.1.WindoW()”,1);)functionscOc1.earinterva1.(timer);)functionScro1.1.windowO(currentpos=document.body.scro1.1.Top:window.scro1.1.(O,+currentpos);if(currentpos!=document,body.scro1.1.Top)sc();document.OnmoUSedOwn=SCdocument,ondb1.c1.ick=initia1.ize<SCRIPT>/41 .后退<INPUTTYPE="button"onc1.ick=window.history.backOva1.ue=back><INPUTTYPE="bu1.1.on"one!ick=window.history,forward()va1.ue=forward>43 .刷新<INPUTTYPE="button"onc1.ick=documen1.1.ocation,re1.oad()va1.ue=re1.oad>44 .转向指定网页document.Iocation="h1.Ip:WW"或者document,1.ocation,assign(*http:/guoguo.COnr)45 .在网页上显示实时时间<SCRIPT1.ANaAGE="JavaScript”)varc1.ock_id;window.on1oad=furction()(c1.ockid=set1.nterva1.("document.,form1.txtc1.ock,vaIue=(newDate)/,1000)<SCRIPT>/document.1。Cation.href="目标文件”47 .连接数据库importjava.sq1.*;StringmyDBDriver=*sun.jdbc.odbc.JdbcOdbcDriver,;C1.ass,forName(myDBDriver);Connectionconn=DriverManager.getConnection(*jdbc:odbc:firm(,“username”,“password");Statementstmt=conn.CreateStatementO:Resu1.tSetrs=stmt.executeQuery(sq1.);rs.getString("co1.umn1.");/48 .可以宜接在页面“div”内写下所需内容<INPUTTYPE="button"onc1.ick=ffa1.innerHTM1.=1<fontco1.or=red>*<font>>”><divid=a1.><div>/49 .可以改变页面上的连接的格式,使其为双线<sty1.e>Ar1.inktext-decoration:none;co1.or:#OOooFF;font-famiIy:宋体Arvisited(text-decora1.ion:none;co1.or:H0000FF;font-fami1.y:宋体Arhovertext-decoraIion:under1.ineoverIine;co1.or:FFOOOO<sty1.e><sty1.e>Ar1.inktext-decoration:none;co1.or:t?OOOOFF;font-famiIy:宋体Arvisitedi,text-decoration:none;co1.or:I100OOFF;font-famiIy:宋体ArhoverIIeX1.-decoration:under!ineover1.ine1ine-through;co1.or:FFOOOOTHFONT-SIZE:9ptTDFONT-SIZE:9pt)bodySCRO1.1.BR-FACE-CO1.OR:9D46D;SCRO1.1.BR-HIGII1.TGHT-CO1.OR:#e7e7e7;SCRO1.1.BAR-SHADOW-CO1.OR:#e7e7e7:SCR01.1.BR-3D1.IGHT-C01.0R:«000000;1.INE-HEIGHT:15pt;SCRO1.1.BAR-ARROW-CO1.OR:ttffffff:SCRO1.1.BAR-TRACK-CO1.OR:tte7e7e7;NPUTBORDER-TOPTIDTH:1.px;PADDING-RIGHT:1.px;PADDING-1.EPT:Ipx;BORDER-1.EFT-WIDTH:Ipx;FONT-SIZE:9pt;BORDER-1.EFT-CO1.OR:ttcccccc:BORDER-BOnOM-WIDTH:1.px;BORDER-BOnOM-CO1.OR:MCCCCCc;PADDING-BOTTOM:Ipx;BORDER-TOP-CO1.OR:Scccccc;PDDING-TOP:Ipx;HEIGHT:18px:BORDER-RIGHT-WIDTH:Ipx;BORDER-RIG1.IT-CO1.OR:甘CCCCCC)DIV,form,OPTION,P,TD1BR(FONT-FAMI1.Y:宋体;FONT-SIZE:9pt)Iextarea,se1.ectborder-wid1.h:1:boder-co1.or:#000000;background-co1.or:Sefefef;font-fami1.y:宋体;font-size:9pt;font-sty1.e:bo1.d:).Iextfont-famiIy:"宋体";font-size:9pt;co1.or:HOO3300:border:#006600so1.id;border-width:IpxIpxIpx1.px/sty1.e完整的css50 .新建frame<ahref=*javascript:newframe('h1.1.prndex.htm,http/a_13.htm)*><iraga1.t=帮助border=0s,c=whttp:/51 .向文件中写内容pageimport=*java.io.*%><%Stringstr=wprintme”;/a1.waysgivethepathfromroot.Thiswayita1.mosta1.waysworks.StringnameOfTextFi1.e="usrani1.imp.txt”;try(PrintWriterPW=newPrintWriter(newFi1.eOutputStream(nameOfTextFi1.e);pw.print1.n(str);/c1.eanuppw.c1.ose();Vara=3454545.4154545;a1.ert(a.toFixed(2);/71 .禁止选择页面上的文字来拷贝<script>functionnoEffect()with(event)returnVa1.ue=fa1se;Cance1.Bubb1.e=true;)return;)<script><bodyonse1.ectstart=",11oEffeet()“OnCQnIeX1.menU="noEffect()*>/72 .屏蔽右键菜单oncontextmenu=wevent.returnVa1.ue=fa1.seV73 .事件禁止起泡event.Cance1.Bubb1.e=true/111111111<textarea>/132 .判断是什么对象if(typeof(unknown)=*function*)returntrue;if(1.ypeof(unknown)!="objec1.")re1.urnfa1.se;/133 .取消文本框自动完成功能<inputtype="text"au1.ocOn1.PIe1.e="off”>/134 .让下拉框自动下拉<se1.ectOnmOUSeOVer="javascript:this,size=this.1.ength*onmouseout=,javascript:this.SiZe=1”<optionva1.ue=*>1.<option><op1.ionva1ue=*>2<option><optionva1.ue=*>3<option><se1.ect>/135,读取XM1.文件varchi1drenobj=myse1ectdocument.a1.1.myse1.ect;varoXM1.Doc=new.ActiveXObject(,MSXM1.,);oXM1.Doc.ur1.=mymsg.xm1.*;var0R00t=0XM1.D0c.root;if(oRoot.chi1.dren!=nu1.1.)(for(vari=0:i<oRoot.chi1.dren,item(0).chi1.dren,1.ength+i)o1.tem=oRoot.chi1.dren,item(0).chi1.dren,item(i);o0ption=newOption(o1.tem.text,o1.tem.va1.ue):Chi1.drenobj.add(oOption);/mymsg.XmI文件<?xm1.version=*1.0*encoding=*gb2312*?><chiIdren1.ist><aa><chiIdva1.ue='3301'>杭州地区<chi1.d><chi1.dVa1.Ue='3303'温州地区<chi1.d><aa><aa><chiIdva1.ue='3310'>台州地区<chi1.d><chi1.dVaIUe='3311'>丽水地区<chid><aa><chiIdren1.ist>/136 .点击图片,图片停止<ahref="xjavascript:*><imgSrC="http:/WWborder="x0w><a>/137 .显示本地计算机信息varWshNetwork=newActiveXObject("WScript.Network);a1.erI("Domain="+WshNetuork.UseiDomain);a1.ert("ComputerName="+WshNetwork.ComputerName);a1.ertCxUserName="+WshNetwork.UserName);/138,比较时间1.Date=newDate(2001,01,08,14,35):/年,月,日,时,分dDate=newDateO;tDate<dDate?a1.ert("早于"):a1.ert("晚于");/139 .弹出鼠标所在处的链结地址<bodyOnmoUSeoVer="if(event.srcE1.ement.tagName=',)a1.er1.(event.srcE1.ement.href)*><ahref=*http140 .注意不能通过与undefined做比较来测试一个变量是否存在,虽然可以检查它的类型是否为“undefined”。在以下的代码范例中,假设程序员想测试是否已经声明变量X:/这种方法不起作用if(x=undefined)/作某些操作/这个方法同样不起作用-必须检查/字符串"undefined*if(typeof(x)=undefined)/作某些操作/这个方法有效if(typeof(x)="undefined")/作某些操作141 .创建具有某些属性的对象varmybject=newObject();mybject.name="James”;mybject.age="22"mybject.phone="5551234”;142 .枚举(循环)对象的所有属性a1.ert('cindy'.1.rim();146,定义一个将口期类型转化为字符串的方法fundionguoguodate()vartmp1.,tmp2;tmp1.=this.getMonth()+1.+*;if(1.mp1.1.ength<2)tmp1.="O"+tmp1.;ImP2=this.getDate()+*;if(tmp2.1.ength<2)ImP2="0"+tmp2;returnthis.getYear()+*-*+tmp1.+*-,+tmp2;)Date,prototype.to1.iteString=guoguodate;a1.ert(newDateO.to1.iteString()147.pasta是有四个参数的构造器,定义对象。functionpasta(grain,width,shape,hasEgg)/是用什么粮食做的?this,grain=grain;/多宽?(数值)this.width=width;横截面形状?(字符串)this,shape=shape;/是否加蛋黄?(boo1.ean)this.hasEgg=hasEgg;定义方法this.toString=aa;functionaa().)定义了对象构造器后,用new运算符创建对象实例。varspaghetti=newPaSta("whea1.”,O.2,“circ1.e”,true);var1inguine=newpasta("wheat*,O.3,“ova1.”,true);/补充定义属性,spaghetti和IingUine都将自动获得新的属性pasta,prototype,foodgroup="carbohydrates”;118.打印出错误原因try(X=y/产生错误。catch(e)document,write(e.description)打印"'y'isundefined*./149.生成EXCE1.文件并保存varExce1.Sheet;Exce1.App=newActiveXObject(*Exce1.pp1.ication);Exce1.Sheet=newActiveXObject(Exce1.Sheet,);/本代码启动创建对象的应用程序(在这种情况下,MicrOSQf1.Exce1.工作表)。一旦对象被创建,就可以用定义的对151 .实现打印预览及打印<OBJECTc1.assid=C1.SID:8856F961-340-11)0-A96B-00C04FD7052,height=Oid=wbname=wbWidth=OX/OBJECT<inputtype=buttonVaIUe=打印预览onc1.ick=*wb.execwb(7,1)*><inputtype=buttononC1.ick=docment.a1.1.wb.ExecWB(6,1)va1.ue=*打印”>152 .不通过form,直接通过名字引用对象<INPUTTYPE="text"NAME="gg"va1.e=aaaaa><SCRIPT1.ANGUAGE=*JavaScript*><!a1.ert(document,a1.1.gg.va1.ue)/-><SCRTPT>/153 .使鼠标滚轮失效functiondocument,onmousewhee1.Oreturnfa1.se;)/158 .向下拉框指定位置添加项目varOP=document.CreateE1.ement(wOPTIONw);document,a1.1.se1.ectedi1.ems,chiIdien(index).insertAdJacentE1.ement("BeforeBegin”,op);op.text=document,a1.1.a1.1itemsi.text;op.va1.ue=document,a1.1.a1.1._itemsi.va1.ue;/159 .判断一个窗口是否已经打开,如果已经打开,则关闭之vara;if(八)a.c1.ose();e1.sea=window.open(,160 .动态创建一个标签newE1.em=document.CreateE1.ement(z,DIV*);newE1.em.id=*hint_1.ayer*;document,body.appendChi1d(newE1em);document,a1.1.hint_1.ayer.innerText="guoguo”;161.标题栏document,titie/162 .背景图片<bodystyIe=zrBAcKGROUND-ATTACHMENT:fixecbackground=*img/bgfix.gif*Xbody>/背景图片不动<STY1.ETYPE="textcss”><!BODYbackground-image:img/bgchiId.jpg;backgrounc1.-position:center;background-repeat:no-repeat;background-attachment:fixed;>GSTY1.E背景图片居中163 .设置透明效果document,form.xxx.fiIters,a1.pha.OPaCi1.y=O100164 .定义方法vardragapproved=fa1.se;document,onmouseup=newFunction(z,dragapproved=fa1.se*);/165 .将数字转化为人民币大写形式functionConvertCurrency(currencyDigits)/Constants:varmaximum_number=99999999999.99;/Predefinetheradixchaactersandcurrencysymbo1.sfo,output:varCN_ZERO="零";varCNONE="壹";varCNJTWO="贰";varCNTHREE="叁"varCr1.FOUR="肆";varCNFIVE="伍";varCN_SIX="陆"varCNSEVEN="柒";varCN_EIGHT="捌"varCNNINE="玖";varCNjrEN="抬";varCNHUNDRED="佰";varCNjHOUSAND="仟";varCNTENTHOUSAND="万";varCnjiundredjh1.1.ion="亿";varCNSYMBO1.,="人民币"varCN_DO1.1.AR="元";returnif(currencyDigits).match(d1.,3(,d3)*(.(d3,)*d(1.,3)?)I(d+(.d+)?)$/)=nu1.1.)a1.ert(I1.1.ega1.formatofdigitnumber!,);return:/Norma1.izetheformatofinputdigits:CurrencyDigits=CurrencyDigits.rep1.ace(/,g,;/Removecommade1.imiters.CurrencyDigits=CurrencyDigits.rep1.ace(/0+/,;/Trimzerosatthebeginning./Assertthenumberisnotgreaterthanthemaximumnumber.if(Number(CurrencyDigits)>MAXIMUb1.NUMBER)a1.ert("Too1.argeanumbertoconvert.!”);return"”;/Processthecoversionfromcuencydigitstocharacters:/Separateintegra1.anddecima1.partsbeforeprocessing/Processintegra1.partifitis1.argerthan0:if(Number(integra1.)>0)(ZeroCount=O;for(i=O;i<integra1.,1.ength:i+)p=integra1.,1.ength-i-1;d=integra1.,substr(i,1);quotient=p/4;modu1.us=p%4;if(d="O")ZeroCount+;e1.seif(ze-oCount>O)OutputCharacters+=digitsO;)ZeroCount=O;outputcharacters+=digitsNumber(d)+radicesmodu1.us;if(modu1.us=O&&ZeroCount<4)OUtputCharacters+=bigRadicesquotient;<PRICE>9.90<PRICE><YEAR>1988<YEAR><CD><CD><TIT1.E>Greatest1.1.its<TIT1.E><ARTIST>Do1.1.yParton<ARTIST><COUNTRY>USA<CO1.NTRY><COMPANY>RCA<COMPANY><PRICE>9.90<PRICE><YEAR>1982<YEAR><CD><CD><TIT1.E>Sti1.1.gottheb1.ues<TIT1.E><ARTIST>GaryMoore<RTIST><COUNTRY>UK<CO1.NTRY><COMPANY>Virginrecords<COMPNY><PRICE>10.20<PRICE><YEAR>1990<YEAR><CD><CATA1.OG>/录集X.abso1.uteposition是从1到记录集记录的个数的guoguo.innerText=xm1.dso.recordset("fie1.d_name");/从中取出某条记录)<script>169 .动态修改CSS的另一种方式this.runtimeSty1.e.cssText=*co1.or:s990000:border:Ipxso1.idCCCeC”;170 .正则表达式匹配中文字符的正则表达式:u4e00-u9fa5匹配双字节字符(包括汉字在内):xOO-xff应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)String,prototype,1.en=function()returnthis,rep1.ace(xOO-xffg,*aa*).1.ength;String.prototype.1.rim=1.'unction()returnthis,rep1.ace(/(s*)(s*$)/g,;a1.ertC,.trim)/195 .防止网页被包含if(window!=window,top)top.1