常用JavaScript
以下整理的JavaScript常用的脚本,有需要的朋友可以收藏了喔~
1.让文字不停地滚动
<MARQUEE>滚动文字</MARQUEE>
2.记录并显示网页的最后修改时间
<script language=javascript> document.write("最后更新时间: " + document.lastModified + ""); </script>
3.关闭当前窗口
<a href="#" onClick="javascript :window.close();return false;">关闭窗口</a>
4.5秒后关闭当前页
<script language="javascript"> <!-- setTimeout('window.close();',5000); --> </script>
5.2秒后载入指定网页
<head> <meta http-equiv="refresh" content="2;URL=http://你的网址"> </head>
6.添加到收藏夹
<Script Language="javascript"> function bookmarkit(){ window.external.addFavorite('http://你的网址','你的网站名称'); } if (document.all){ document.write('<a href="#" onClick="bookmarkit()">加入收藏夹</a>'); } </Script>
7.让超链接不显示下划线
<style type="text/css"> <!- a:link{text-decoration:none} a:hover{text-decoration:none} a:visited{text-decoration:none} -> </style>
8.禁止鼠标右键的动作
<script language="javascript"> function click() { if (event.button==2||event.button==3){ alert('禁止鼠标右键'); } } document.onmousedown=click; </script>
9.设置该页为首页
<span onclick="var strHref=window.location.href;this.style.behavior=
'url(#default#homepage)';
this.setHomePage('http://www.cnblogs.com/xiaoyu5062/');
" style="CURSOR: hand"><br>将本站设置为首页</span>
10.节日倒计时
<Script Language="javascript"> var timedate= new Date("December 25,2008"); var times="圣诞节"; var now = new Date(); var date = timedate.getTime() - now.getTime(); var time = Math.floor(date / (1000 * 60 * 60 * 24)); if (time >= 0) document.write("现在离"+times+"还有: "+time +"天") </Script>
11.单击按钮打印出当前页
<Script Language="javascript"> if (window.print) { document.write('<form>' + '<input type=button name=print value="打印本页" ' + 'onClick="javascript:window.print();"></form>'); } </Script>
12.单击按钮‘另存为’当前页
<input type="button" name="Button" value="保存本页" onClick="document.all.button.ExecWB(4,1)"> <object id="button" width=0 height=0 classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"> <embed width="0" height="0"></embed> </object>
13.显示系统当前日期
<script language=javascript> var today=new Date(); function myDate(){ this.week=new Array(); this.week[0]="星期日"; this.week[1]="星期一"; this.week[2]="星期二"; this.week[3]="星期三"; this.week[4]="星期四"; this.week[5]="星期五"; this.week[6]="星期六"; this.getWeek=function(num){ return this.week[num]; } } var d = new myDate(); document.write( "<font color=##000000 style='font-size:9pt;font-family: 宋体'> ", today.getYear(),"年",today.getMonth()+1,"月",today.getDate(),"日", d.getWeek(today.getDay()),"</font>" ); </script>
14.不同时间段显示不同问候语
<Script Language="javascript"> <!-- var text=""; day = new Date( ); time = day.getHours( ); if (( time>=0) && (time < 7 )){ text="夜猫子,要注意身体哦! " } if (( time >= 7 ) && (time < 12)){ text="今天天气……哈哈哈,不去玩吗?" } if (( time >= 12) && (time < 14)){ text="午休时间哦,朋友一定是不习惯午睡的吧?!" } if (( time >=14) && (time < 18)){ text="下午茶的时间到了,休息一下吧! " } if ((time >= 18) && (time <= 22)){ text="您又来了,可别和MM聊太久哦!" } if ((time >= 22) && (time < 24)){ text="很晚了哦,注意休息呀!" } document.write(text) //---> </Script>
15.水中倒影效果
<img id="reflect" src="你自己的图片文件名" width="175" height="59"> <script language="javascript"> function f1() { setInterval("mdiv.filters.wave.phase+=10",100); } if (document.all) { document.write('<img id=mdiv src="'+document.all.reflect.src+'" style="filter:wave(strength=3,freq=3,phase=0,lightstrength=30) blur() flipv()">'); window.onload=f1 } </script>
16.慢慢变大的窗口
<Script Language="javascript"> <!-- var Windowsheight=100; var Windowswidth=100; var numx=5; function openwindow(thelocation){ temploc=thelocation; if (!(window.resizeTo&&document.all)&&!(window.resizeTo&&document.getElementById)) { window.open(thelocation); return; } windowsize=window.open("","","scrollbars"); windowsize.moveTo(0,0); windowsize.resizeTo(100,100); tenumxt(); } function tenumxt(){ if (Windowsheight>=screen.availHeight-3){ numx=0; } windowsize.resizeBy(5,numx); Windowsheight+=5; Windowswidth+=5; if (Windowswidth>=screen.width-5) { windowsize.location=temploc; Windowsheight=100; Windowswidth=100; numx=5; return; } setTimeout("tenumxt()",50); } //--> </script> <p><a href="javascript:openwindow('http://www.cnblogs.com/xiaoyu5062/')">进入</a>
17.改变IE地址栏的IE图标
我们要先做一个16*16的icon(图标文件),保存为index.ico。把这个图标文件上传到根目录下,
并在首页<head></head>之间加上如下代码:
<head> <link rel="Shortcut Icon" href="index.ico"/> </head>
18:进入或者离开时显示信息
设置body的 onLoad和onUnload事件
19:只能输入数字
<script LANGUAGE="javascript">; <!-- function check(){ if (document.form.tell.value==""){ alert("请输入数字!"); document.form.tell.focus(); return false; }else{ var Letters = "0123456789()+-"; for (i=0; i< document.form.tell.value.length; i++){ var CheckChar = document.form.tell.value.charAt(i); if (Letters.indexOf(CheckChar) == -1){ alert("输入的数字不正确!"); document.form.tell.focus(); return false; } } } } //-->; </script> <form method="POST" name=form action="" onSubmit="return check();"> 请输入数字:<input type="text" name="tell" size="20"> <input type="submit" value="提交" name="B1"> </form>
20:email 合法性检查
<script language="javascript"> function check() { var vv = document.all("email").value; if(vv.length!=0) { if (vv.charAt(0)=="." || vv.charAt(0)=="@"|| vv.indexOf('@', 0) == -1 || vv.indexOf('.', 0) == -1 || vv.lastIndexOf("@") ==vv.length-1 || vv.lastIndexOf(".") ==vv.length-1) { alert("Email的格式不正確!"); document.all("email").focus(); return false; } } else { alert("Email的不能为空!"); document.all("email").focus(); return false; } return false; } </script> <input type="text" name="email"> <input type="button" onclick="check();" value="检查email">
21:屏蔽 Ctrl+N、Shift+F10、F5刷新、退格键
<script language="javascript"> <!-- //屏蔽鼠标右键、Ctrl+N、Shift+F10、F5刷新、退格键 function window.onhelp(){return false} //屏蔽F1帮助 function KeyDown(){ if ((window.event.altKey)&& ((window.event.keyCode==37)|| //屏蔽 Alt+ 方向键 ← (window.event.keyCode==39))){ //屏蔽 Alt+ 方向键 → alert("不准你使用ALT+方向键前进或后退网页!"); event.returnvalue=false; } /* 注:这还不是真正地屏蔽 Alt+ 方向键, 因为 Alt+ 方向键弹出警告框时,按住 Alt 键不放, 用鼠标点掉警告框,这种屏蔽方法就失效了。以后若 有哪位高手有真正屏蔽 Alt 键的方法,请告知。*/ if ((event.keyCode == 8) && (event.srcElement.type != "text" && event.srcElement.type != "textarea" && event.srcElement.type != "password") || //屏蔽退格删除键 (event.keyCode==116)|| //屏蔽 F5 刷新键 (event.ctrlKey && event.keyCode==82)){ //Ctrl + R event.keyCode=0; event.returnvalue=false; } if ((event.ctrlKey)&&(event.keyCode==78)) //屏蔽 Ctrl+n event.returnvalue=false; if ((event.shiftKey)&&(event.keyCode==121)) //屏蔽 shift+F10 event.returnvalue=false; if (window.event.srcElement.tagName == "A" && window.event.shiftKey) window.event.returnvalue = false; //屏蔽 shift 加鼠标左键新开一网页 if ((window.event.altKey)&&(window.event.keyCode==115)){ //屏蔽Alt+F4 window.showModelessDialog("about:blank","","dialogWidth:1px;dialogheight:1px"); return false;} } /* 另外可以用 window.open 的方法屏蔽 IE 的所有菜单 第一种方法: window.open("你的.htm", "","toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,resizable=yes,status=no,top=0,left=0") 第二种方法是打开一个全屏的页面: window.open("你的.asp", "", "fullscreen=yes") */ //--> </script> <input type="text" >
22:屏蔽F5键
<script language="javascript"> <!-- function document.onkeydown() { if ( event.keyCode==116) { event.keyCode = 0; event.cancelBubble = true; return false; } } --> </script> <input type="text">
23:屏蔽主窗口滚动条
在body标签里加上
style="overflow-y:hidden"
24:取得控件的绝对位置
<script language="javascript"> function getIE(e){ var t=e.offsetTop; var l=e.offsetLeft; while(e=e.offsetParent){ t+=e.offsetTop; l+=e.offsetLeft; } alert("top="+t+"nleft="+l); } </script> <input type="button" value="看看我的位置" onclick="getIE(this);">
25:切换页面后,光标停在文本框文字的最后
<script language="javascript"> function cc() { var e = event.srcElement; var r =e.createTextRange(); r.moveStart("character",e.value.length); r.collapse(true); r.select(); } </script> <input type=text name=text1 value="123" onfocus="cc();">
26:表格的半透明显示效果
在<head></head>之间加上如下代码:
<style> .alpha{filter: Alpha(Opacity=50)} //50表示50%的透明度 </style>
在<body></body>之间加上如下代码:
<table border="1" width="100" height="62" class="alpha" bgcolor="#F2A664" > <tr> <td width="100%" height="62"> <div align="center">很酷吧!</div> </td> </tr> </table>
27:细线分隔线
<hr noshade size=0 color=#C0C0C0>
28:过渡度方式
<head> <meta http-equiv="Page-Exit" content="revealTrans(Duration=3,Transition=3)"> </head> <a href="b.html">to b.html</a>
Duration的值为网页动态过渡的时间,单位为秒。
Transition是过渡方式,它的值为0到23,分别对应24种过渡方式。如下表:
0 盒状收缩 1 盒状放射
2 圆形收缩 3 圆形放射
4 由下往上 5 由上往下
6 从左至右 7 从右至左
8 垂直百叶窗 9 水平百叶窗
10 水平格状百叶窗 11垂直格状百叶窗
12 随意溶解 13从左右两端向中间展开
14从中间向左右两端展开 15从上下两端向中间展开
16从中间向上下两端展开 17 从右上角向左下角展开
18 从右下角向左上角展开 19 从左上角向右下角展开
20 从左下角向右上角展开 21 水平线状展开
22 垂直线状展开 23 随机产生一种过渡方式
29:如何控制横向和纵向滚动条的显隐?
<body style="overflow-y:hidden"> <!--去掉x轴--> <body style="overflow-x:hidden"> <!--去掉y轴 --> <body scroll="no"><!--不显-->
30:javascript中获取地址栏参数比如 index.jsp?id=xxx&name=xxx
方法一:
<script> function getvalue(name) { var str=window.location.search; if (str.indexOf(name)!=-1) { var pos_start=str.indexOf(name)+name.length+1; var pos_end=str.indexOf("&",pos_start); if (pos_end==-1) { return str.substring(pos_start); } else { return str.substring(pos_start,pos_end) } } else { return "没有这个name值"; } } var strName=prompt("请输入您所要值的名字"); alert(getvalue(strName)); </script>
方法二:
<script language="javascript"> var URLParams = new Array(); var aParams = document.location.search.substr(1).split('&'); for (i=0;i<aParams.length;i++){ var aParam = aParams[i].split("="); URLParams[aParam[0]] = aParam[1]; } //取得传过来的name参数 var v=URLParams["name"]; alert("name==="+v); </script>
方法三:
<script type="text/javascript"> Request = { QueryString : function(item){ var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i")); return svalue ? svalue[1] : svalue; } } alert(Request.QueryString("name")); </script>
31:window对象的方法
open(URL,WindowName,parameterList):open方法创建一个新的浏览器窗口,并在新窗口中载入一个指定的URL地址。
close():close方法关闭一个浏览器窗口.
alert(text):弹出一个信息框.
confirm(text):弹出一个确认框.
prompt(text,Defaulttext):弹出一个提示框.
setTimeout(expression,time):定时设置,在一定时间后自动执行expression描述的代码,使用time设置时间,单位是毫秒.
clearTimeout(timer):取消以前的定时设置.
back():指示浏览器载入历史记录中的上一个URL地址.
forward():指示浏览器载入历史记录中的下一个URL地址.
stop():指示浏览器停止网页的装载.
location:提供当前窗口的URL信息
history:提供当前窗口的历史记录,可以在网页导航中发挥作用.
closed:一个指出窗口目前是否关闭的逻辑值.
self:引用当前文档对应的窗口.
navigate(url):窗口转向另外一个窗口
32:验证是否整数
<script type="text/javascript"> function checkInteger(v){ var s = ""+v; var ret = s.match(/^(-|\+)?\d+$/); if(ret==null){ alert(v+" , 不是数字"); } } checkInteger('01230'); checkInteger("abc"); </script>
33:验证是否都是数字,而且是正整数
<script type="text/javascript"> function checkGreaterZero(v){ var s = ""+v; var ret = s.match(/^\d+$/); if(ret==null){ alert(v+" , 不是数字"); } } checkGreaterZero('1230'); checkGreaterZero("abc"); </script>
34:验证是否都是数字,而且是负整数
<script type="text/javascript"> function checkLitterZero(v){ var s = ""+v; var ret = s.match(/^-\d+$/); if(ret==null){ alert(v+" , 不是小于0的数字"); } } checkLitterZero('-1230'); checkLitterZero("123"); </script>
35:短时间,形如 (13:04:06)
<script language="javascript"> function isTime(str) { var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/); if (a == null) {alert('输入的参数不是时间格式'); return false;} if (a[1]>24 || a[3]>60 || a[4]>60) { alert(str+",时间格式不对"); return false } return true; } isTime("12:09:39"); isTime("33:55:99"); </script>
36:短日期,形如 (2008-12-05)
<script language="javascript"> function strDateTime(str) { var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); if(r==null)return false; var d= new Date(r[1], r[3]-1, r[4]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]); } alert(strDateTime("2008-10-28")); alert(strDateTime("08-12-9")); </script>
37:长时间,形如 (2003-12-05 13:04:06)
<script language="javascript"> function strDateTime(str) { var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/; var r = str.match(reg); if(r==null)return false; var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]); } alert(strDateTime("2008-10-28 11:11:11")); alert(strDateTime("08-12-9 11:11:11")); </script>
38:检测值不能为空
<script language="javascript"> function canNotEmpty(str) { if(str.replace(/^\s+|\s+$/g,'')==''){ alert('不能为空!'); } return true; } alert(canNotEmpty("2008-10-28 11:11:11")); alert(canNotEmpty(" ")); </script>
39:判断字符全部由a-Z或者是A-Z的字字母组成
<script language="javascript"> function isLetter(str) { if(/[^a-zA-Z]/g.test(str)){ return false; } return true; } alert(isLetter("aaaSSFsadfa")); alert(isLetter("a3d")); </script>
40:判断字符由字母和数字组成
<script language="javascript"> function isLetter(str) { if(/[^0-9a-zA-Z]/g.test(this.value)){ return false; } return true; } alert(isLetter("aaaSSFsadfa")); alert(isLetter("a3d")); </script>
41:判断字符由字母和数字,下划线,点号组成.且开头的只能是下划线和字母
<script language="javascript"> function isLetter(str) { if(/^([a-zA-z_]{1})([\w]*)$/g.test(str)){ return true; } return false; } alert(isLetter(" aaaSSFsadfa")); alert(isLetter("_a3d")); </script>
42:判断浏览器的类型
<script language="javascript">
alert(window.navigator.appName);
</script>
43:判断ie的版本
<script language="javascript">
alert(window.navigator.appVersion);
</script>
44:判断客户端的分辨率
<script language="javascript">
alert(window.screen.height);
alert(window.screen.width);
</script>
45:用正则表达式判断是否Email
<script language="javascript"> function isMail(mail) { return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(mail)); } alert(isMail("cc@a.com")); alert(isMail("cc 1@a.com")); </script>
46:用正则表达式判断是否身份证号码
<script language="javascript"> function isIdCardNo(num) { if (isNaN(num)) {alert("输入的不是数字!"); return false;} var len = num.length, re; if (len == 15) re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/); else if (len == 18) re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d)$/); else {alert("输入的数字位数不对!"); return false;} var a = num.match(re); if (a != null) { if (len==15) { var D = new Date("19"+a[3]+"/"+a[4]+"/"+a[5]); var B = D.getYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5]; } else { var D = new Date(a[3]+"/"+a[4]+"/"+a[5]); var B = D.getFullYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5]; } if (!B) {alert("输入的身份证号 "+ a[0] +" 里出生日期不对!"); return false;} } return true; } alert(isIdCardNo("511111199001013456")); alert(isIdCardNo("511111199013313456")); </script>
47:给表格自动增行(msdn的例子)
<SCRIPT> function createRows(){ // insert two rows. var oRow1=oTable.insertRow(oTable.rows.length); var oRow2=oTable.insertRow(oTable.rows.length); // retrieve the rows collection for the table. var aRows=oTable.rows; // retrieve the cells collection for the first row. var aCells=oRow1.cells; // insert two cells into the first row. var oCell1_1=aRows(oRow1.rowIndex).insertCell(aCells.length); var oCell1_2=aRows(oRow1.rowIndex).insertCell(aCells.length); // retrieve the cells collection for the second row. aCells=oRow2.cells; // insert two cells into the second row. var oCell2_1=aRows(oRow2.rowIndex).insertCell(aCells.length); var oCell2_2=aRows(oRow2.rowIndex).insertCell(aCells.length); // Add regular HTML values to the 4 new cells. oCell1_1.innerHTML="<B>Cell 1.1!</B>"; oCell1_2.innerHTML="<B>Cell 1.2!</B>"; oCell2_1.innerHTML="<B>Cell 2.1!</B>"; oCell2_2.innerHTML="<B>Cell 2.2!</B>"; } </SCRIPT> <INPUT TYPE="button" VALUE="Create Rows" onclick="createRows()"> <TABLE BORDER=1 ID="oTable"> </TABLE>
48:严格的身份证验证
<script> var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"xizang",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"} function cidInfo(sId){ var iSum=0 var info="" if(!/^\d{17}(\d|x)$/i.test(sId))return false; sId=sId.replace(/x$/i,"a"); if(aCity[parseInt(sId.substr(0,2))]==null)return "Error:非法地区"; sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); var d=new Date(sBirthday.replace(/-/g,"/")) if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "Error:非法生日"; for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) if(iSum%11!=1)return "Error:非法证号"; return aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女") } document.write(cidInfo("380524198002300016"),"<br/>"); document.write(cidInfo("340524198002300019"),"<br/>") document.write(cidInfo("340524197711111111"),"<br/>") document.write(cidInfo("34052419800101001x"),"<br/>"); </script>
49:验证IP地址
<SCRIPT LANGUAGE="JavaScript"> function isip(s){ var check=function(v){try{return (v<=255 && v>=0)}catch(x){return false}}; var re=s.split(".") return (re.length==4)?(check(re[0]) && check(re[1]) && check(re[2]) && check(re[3])):false } var s="202.197.78.129"; alert(isip(s)) </SCRIPT>