`
ayaya
  • 浏览: 450104 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

JS总结二

阅读更多
25.在打开的子窗口刷新父窗口的代码里如何写?
window.opener.location.reload()

26.如何设定打开页面的大小
<body onload="top.resizeTo(300,200);">
打开页面的位置<body onload="top.moveBy(300,200);">

27.在页面中如何加入不是满铺的背景图片,拉动页面时背景图不动
<STYLE>
body
{background-image:url(logo.gif); background-repeat:no-repeat;

background-position:center;background-attachment: fixed}
</STYLE>

28. 检查一段字符串是否全由数字组成
<script language="Javascript"><!--
function checkNum(str){return str.match(//D/)==null}
alert(checkNum("1232142141"))
alert(checkNum("123214214a1"))
// --></script>

29. 获得一个窗口的大小
document.body.clientWidth; document.body.clientHeight

30. 怎么判断是否是字符
if (/[^/x00-/xff]/g.test(s)) alert("含有汉字");
else alert("全是字符");

31.TEXTAREA自适应文字行数的多少
<textarea rows=1 name=s1 cols=27 onpropertychange="this.style.posHeight=this.scrollHeight">
</textarea>

32. 日期减去天数等于第二个日期
<script language=Javascript>
function cc(dd,dadd)
{
//可以加上错误处理
var a = new Date(dd)
a = a.valueOf()
a = a - dadd * 24 * 60 * 60 * 1000
a = new Date(a)
alert(a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日")
}
cc("12/23/2002",2)
</script>

33. 选择了哪一个Radio
<HTML><script language="vbscript">
function checkme()
for each ob in radio1
if ob.checked then window.alert ob.value
next
end function
</script><BODY>
<INPUT name="radio1" type="radio" value="style" checked>Style
<INPUT name="radio1" type="radio" value="barcode">Barcode
<INPUT type="button" value="check" onclick="checkme()">
</BODY></HTML>

34.脚本永不出错
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide
function killErrors() {
return true;
}
window.onerror = killErrors;
// -->
</SCRIPT>

35.ENTER键可以让光标移到下一个输入框
<input onkeydown="if(event.keyCode==13)event.keyCode=9">

36. 检测某个网站的链接速度:
把如下代码加入<body>区域中:
<script language=Javascript>
tim=1
setInterval("tim++",100)
b=1

var autourl=new Array()
autourl[1]="http://www.njcatv.net/"
autourl[2]="javacool.3322.net"
autourl[3]="http://www.sina.com.cn/"
autourl[4]="http://www.nuaa.edu.cn/"
autourl[5]="http://www.cctv.com/"

function butt(){
document.write("<form name=autof>")
for(var i=1;i<autourl.length;i++)
document.write("<input type=text name=txt"+i+" size=10 value=测试中……> =》<input type=text

name=url"+i+" size=40> =》<input type=button value=GO

onclick=window.open(this.form.url"+i+".value)><br/>")
document.write("<input type=submit value=刷新></form>")
}
butt()
function auto(url){
document.forms[0]["url"+b].value=url
if(tim>200)
{document.forms[0]["txt"+b].value="链接超时"}
else
{document.forms[0]["txt"+b].value="时间"+tim/10+"秒"}
b++
}
function run(){for(var i=1;i<autourl.length;i++)document.write("<img
src=http://"+autourl+"/"+Math.random()+" width=1 height=1
onerror=auto("http://"+autourl/+"")>")}
run()</script>

37. 各种样式的光标
auto :标准光标
default :标准箭头
hand :手形光标
wait :等待光标
text :I形光标
vertical-text :水平I形光标
no-drop :不可拖动光标
not-allowed :无效光标
help :?帮助光标
all-scroll :三角方向标
move :移动标
crosshair :十字标
e-resize
n-resize
nw-resize
w-resize
s-resize
se-resize
sw-resize

external.m2_blocked()、external.m2_blocked()方法使用详解

javascript有许多内建的方法来产生对话框,如:window.alert(),
window.confirm(),window.prompt().等。 然而IE提供更多的方法支持对话框。如:

  external.m2_blocked() (IE 4+ 支持)
  external.m2_blocked() (IE 5+ 支持)


window.external.m2_blocked()方法用来创建一个显示HTML内容的模态对话框,
由于是对话框,因此它并没有一般用window.open()打开的窗口的所有属性。
window.external.m2_blocked()方法用来创建一个显示HTML内容的非模态对话框。

当我们用external.m2_blocked()打开窗口时,不必用window.close()去关闭它,
当以非模态方式[IE5]打开时, 打开对话框的窗口仍可以进行其他的操作,即对话框
不总是最上面的焦点,当打开它的窗口URL改变时,它自动关闭。而模态[IE4]
方式的对话框始终有焦点(焦点不可移走,直到它关闭)。模态对话框和打开它的窗
口相联系,因此我们打开另外的窗口时,他们的链接关系依然保存,并且隐藏在活动
窗口的下面。

使用方法如下:
vReturnValue=window.external.m2_blocked(sURL [,vArguments] [,sFeatures])
vReturnValue=window.external.m2_blocked(sURL [,vArguments] [,sFeatures])
参数说明:
sURL
必选参数,类型:字符串。用来指定对话框要显示的文档的URL。
vArguments
可选参数,类型:变体。用来向对话框传递参数。传递的参数类型不限,包括数组等。
对话框通过window.dialogArguments来取得传递进来的参数。
sFeatures
可选参数,类型:字符串。用来描述对话框的外观等信息,可以使用以下的一个或几个,
用分号“;”隔开。
  dialogHeight 对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth
默认的单位是em,而IE5中是px,为方便其见,在定义modal方式的对话框时,用px
做单位。
  dialogWidth: 对话框宽度。
  dialogLeft: 距离桌面左的距离。
  dialogTop: 离桌面上的距离。
  center: {yes | no | 1 | 0 }:窗口是否居中,默认yes,但仍可以指定高度和宽度。
  help: {yes | no | 1 | 0 }:是否显示帮助按钮,默认yes。
  resizable: {yes | no | 1 | 0 } [IE5+]:是否可被改变大小。默认no。
  status: {yes | no | 1 | 0 } [IE5+]:是否显示状态栏。默认为yes[ Modeless]
或no[Modal]。
  scroll:{ yes | no | 1 | 0 | on | off }:指明对话框是否显示滚动条。默认为yes。

  还有几个属性是用在HTA中的,在一般的网页中一般不使用。
  dialogHide:{ yes | no | 1 | 0 | on | off }:在打印或者打印预览时对话框是否隐藏。
默认为no。
  edge:{ sunken | raised }:指明对话框的边框样式。默认为raised。
  unadorned:{ yes | no | 1 | 0 | on | off }:默认为no。

传入参数:
要想对话框传递参数,是通过vArguments来进行传递的。类型不限制,对于字符串类型,
最大为4096个字符。也可以传递对象,例如:

test1.htm
====================
<script>
  var mxh1 = new Array("mxh","net_lover","孟子E章")
  var mxh2 = window.open("about:blank","window_mxh")
  // 向对话框传递数组
  window.external.m2_blocked("test2.htm",mxh1)
  // 向对话框传递window对象
  window.external.m2_blocked("test3.htm",mxh2)
</script>

test2.htm
====================
<script>
  var a = window.dialogArguments
  alert("您传递的参数为:" + a)
</script>

test3.htm
====================
<script>
  var a = window.dialogArguments
  alert("您传递的参数为window对象,名称:" + a.name)
</script>

可以通过window.returnValue向打开对话框的窗口返回信息,当然也可以是对象。
例如:

test4.htm
===================
<script>
  var a = window.external.m2_blocked("test5.htm")
  for(i=0;i<a.length;i++) alert(a[i])
</script>

test5.htm
===================
<script>
function sendTo()
{
  var a=new Array("a","b")
  window.returnValue = a
  window.close()
}
</script>
<body>
<form>
  <input value="返回" type=button onclick="sendTo()">
</form>

常见问题:
1,如何在模态对话框中进行提交而不新开窗口?
如果你 的 浏览器是IE5.5+,可以在对话框中使用带name属性的iframe,提交时可以
制定target为该iframe的name。对于IE4+,你可以用高度为0的frame来作:例子,

test6.htm
===================
<script>
  window.external.m2_blocked("test7.htm")
</script>

test7.htm
===================
if(window.location.search) alert(window.location.search)
<frameset rows="0,*">
  <frame src="about:blank">
  <frame src="test8.htm">
</frameset>

test8.htm
===================
<form target="_self" method="get">
<input name=txt value="test">
<input type=submit>
</form>
<script>
if(window.location.search) alert(window.location.search)
</script>
2,可以通过http://servername/virtualdirname/test.htm?name=mxh方式直接向
对话框传递参数吗?
答案是不能。但在frame里是可以的。
file://屏蔽 F5 刷新键


function document.onkeydown()
{
    var k = window.event.keyCode;
    if (k == 116)                   file://屏蔽 F5 刷新键
    {
        window.event.keyCode    = 0;
        window.event.returnValue= false;
    }
}


<script language="javascript">
file://屏蔽鼠标右键、Ctrl+N、Shift+F10、F5刷新、退格键
file://屏蔽F1帮助
function window.onhelp()
{
   return false
}
function KeyDown()
{
  file://alert(event.keyCode/);
   file://屏蔽 Alt+ 方向键 ← 屏蔽 Alt+ 方向键 →
  if ((window.event.altKey)&&((window.event.keyCode==37)||
(window.event.keyCode==39)))
  {  
     file://alert/("不准你使用ALT+方向键前进或后退网页!");
     event.returnValue=false;
  }
  file://屏蔽退格删除键,屏蔽 F5 刷新键,Ctrl + R
  if ((event.keyCode==116)||(event.ctrlKey && event.keyCode==82))
  { 
     event.keyCode=0;
     event.returnValue=false;
  } 
  
  file://屏蔽 Ctrl+n
  if ((event.ctrlKey)&&(event.keyCode==78))
  {  
     event.returnValue=false;
  }
  
  file://屏蔽 shift+F10
  if ((event.shiftKey)&&(event.keyCode==121))
  { 
     event.returnValue=false;
  }
  
  file://屏蔽 shift 加鼠标左键新开一网页
  if (window.event.srcElement.tagName == "A" && window.event.shiftKey) 
  {
    window.event.returnValue = false;
  }
      
   file://屏蔽Alt+F4
  if ((window.event.altKey)&&(window.event.keyCode==115))
  {
      window.external.m2_blocked("about:blank","","dialogWidth:1px;dialogheight:1px");
      return false;
  }
  
  file://屏蔽Ctrl+A
  if((event.ctrlKey)&&(event.keyCode==65))
  {
   return false;
  }
    
}
</script>
</body>
</HTML> 

一些搜集的WEB技术小窍门
如何在HTML文件中包含某个HTML文件?
方法一:
在html 页面 include 其它页面
<IE:Download ID="oDownload" STYLE="behavior:url(#default#download)" />
<body onload="oDownload.startDownload('tt.htm',onDownloadDone)">
<span id=showImport></span>
<script language=javascript><!--
function onDownloadDone(downDate)
{
  document.all.showImport.innerHTML=downDate; //这种方法被讨论出来是最好的
}
//--></script>
方法二:
<object data="vister/count.asp" type="text/x-scriptlet" width="158" height="50" align="top" marginWidth=0 marginHeight

=0>
</object>
----------------------------------------------------------------------------------------------------------------------------

-------------------------------------------
TextBox里加入图片?
<TEXTAREA rows=8 cols=20 id=textarea1 >
大家好!
这里是一个图片
</TEXTAREA>

<SCRIPT LANGUAGE=javascript>
<!--
var img = document.createElement("IMG");
img.src = "http://community.csdn.net/images/csdn.gif";
window.textarea1.appendChild(img);
//-->
</SCRIPT>


全屏技术:
真正的全屏页面解决之道!(全代码) 
真正全屏解决之道: 
1.htm 
<html> 
<head> 
<title>无标题文档</title> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
</head> 

<body onload="window.open('fullscreen.htm','','fullscreen=1,scroll=no');"> 
</body> 
</html> 


fullscreen.htm 
<html> 
<head> 
<title>无标题文档</title> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
<script language="javascript1.2">  
<!--  
function opensmallwin(myurl){  
var w2=300;//想弹出窗口的宽度  
var h2=100;//想弹出窗口的高度  
var w3=window.screen.width/2-w2/2;  
var h3=window.screen.height/2-h2/2;  
window.open(myurl,'small','toolbar=no,location=no,directories=no,status=no,menubar=no,
scrollbars=no,resizable=0,width='+ w2 +',height='+ h2 +',left='+ w3 +',top='+ h3 +'');  
}  
file://-->  

<!-- 
function modelesswin(url,mwidth,mheight){ 
  if (document.all&&window.print) 
    eval('window.external.m2_blocked(url,"","help:0;resizable:0;status:0;center:1;
scroll:0;dialogWidth:'+mwidth+'px;dialogHeight:'+mheight+'px")')  
  else 
    eval('window.open(url,"","width='+mwidth+'px,height='+mheight+'px,resizable=1,
scrollbars=1")') 
  } 
file://--> 

</script>  
</head> 

<body  scroll="no"> 
<div align="right"><a href="javascript:" onclick="window.close()">关闭
</a> </div> 
<p></P> 
<div align="right"><a href="javascript:" onclick="opensmallwin('login.htm')">登录
</a> </div> 

<p></P> 
<div align="center"><a href="javascript:"
onclick="modelesswin('login.htm',300,160)">用模态登录窗口</a> </div> 
</body> 
</html> 


login.htm 
<html> 
<head> 
<title>用户登录</title> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 

<style type="text/css"> 
<!-- 
body { 
   background-color: #EAEAEA; 
   font-family: Arial, Helvetica, sans-serif; 
   font-size: 12px; 
   line-height: 24px; 
   color: #336699; 

input.boxline { 
   width: 100px; 
   font-family: "Times New Roman", "Times", "serif"; 
   font-size: 9pt; 
   border: 1px solid #669999; 
   height: 18px; 



input.whiteline {   
   font-size: 12px; border: 1px #999999 solid 

--> 
</style></head> 
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> 
<table width="100%" height="100%" border="0" cellpadding="0"
cellspacing="14" bgcolor="#CCCCCC"> 
  <tr valign="top"> 
    <td width="10%" nowrap  align="right"><b>用户名:</b></td> 
    <td width="90%"><input name="textfield1" type="text" size="25"
class="whiteline"></td> 
  </tr> 
  <tr valign="top"> 
    <td nowrap align="right"><b>密 码:</b></td> 
    <td><input name="textfield12" type="password" size="25"
class="whiteline"></td> 
  </tr> 
  <tr valign="top"> 
    <td> </td> 
    <td><input type="submit" name="Submit" value="登  录"
class="boxline"></td> 
  </tr> 
</table> 
</body> 
</html> 


自动关掉原窗口: 


<html> 
<head> 
<title>无标题文档</title> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
<style type="text/css"> 
<!-- 
body { 
   margin-left: 0px; 
   margin-top: 0px; 
   margin-right: 0px; 
   margin-bottom: 0px; 

--> 
</style> 
</head> 

<body onload="window.open('fullscreen.htm','','fullscreen=1,scroll=no');
window.opener=null;window.close()"> 
<input type=button value=关闭 onclick="window.opener=null;window.close()">  
<!-- IE5.5+ 不会有弹出提示 -->  

<OBJECT id=WebBrowser classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2
height=0 width=0></OBJECT>  
<input type=button value=关闭窗口 onclick=document.all.WebBrowser.ExecWB(45,1)>  
</body> 
</html> 

关键是在onload事件中加入: 
window.opener=null;window.close() 


预读图片:
<SCRIPT LANGUAGE="javascript">

<!-- This script and many more are available free online at -->
<!-- The javascript Source!! <a href=http://javascript.internet.com
target=_blank>http://javascript.internet.com -->

<!-- Begin

image1 = new Image();
image1.src = "image1.gif";

image2 = new Image();
image2.src = "image2.gif";

// End -->
</script>



关于两个网页刷新交互的问题 
JS处理方法: 

a.htm 

<a href="b.htm" target=blank>发表留言</a> 
<script> 
alert("wwwwwwwwwwwwwwwwwwwwwwwwww"); 
</script> 

b.htm 

<script language="javascript"> 
file://window.opener.location.reload/();刷新父窗口 
file://window.opener.location="2.htm"//重定向父窗口到2.htm页 
function closewindow() 

window.opener.location.reload(); 
self.close(); 
window.opener.document.write("sssssssssssssssssss"); 

</script> 
<a href="b.htm" target=blank onclick="closewindow();">关闭</a> 



后台处理方法: 

private btnForSubmit(Object sender,EventArgs e) 

............. 
Response.Write("<script>window.opener.document.execCommand('refresh');
window.opener='';window.close();</script>"); 
file://string/ str="<script>window.opener.document.execCommand('refresh');
window.opener='';window.close();</script>"; 
file://this.RegisterStartupScript("mycode",str/);

BS开发中常用的javascript技术


4、事件类
  4.1 屏蔽右键
      在body标签里加上oncontextmenu=self.event.returnValue=false  
  4.2 屏蔽所有功能键

  4.3 --> 和<-- F5 F11,F9,F1

  4.4 屏蔽组合键ctrl+N

<script language=javascript>
function KeyDown(){   
  if ((window.event.altKey)&&
      ((window.event.keyCode==37)||   file://屏蔽 Alt+ 方向键 ←
       (window.event.keyCode==39))){  file://屏蔽 Alt+ 方向键 →
     alert("不准你使用ALT+方向键前进或后退网页!");
     event.returnValue=false;
     }
  if ((event.keyCode==8)||            file://屏蔽退格删除键
      (event.keyCode==116)){          file://屏蔽 F5 刷新键
     event.keyCode=0;
     event.returnValue=false;
     }
  if ((event.ctrlKey)&&(event.keyCode==78)){   file://屏蔽 Ctrl+n
     event.returnValue=false;
     }
  if ((event.shiftKey)&&(event.keyCode==121)){ file://屏蔽 shift+F10
     event.returnValue=false;
     }
  if (event.keyCode==122){ file://屏蔽 F11
     event.returnValue=false;
     }
  }
只要知道keyCode即可屏蔽所有功能键


一、验证类
1、数字验证内
  1.1 整数
      /^(-|\+)?\d+$/.test(str)
  1.2 大于0的整数 (用于传来的ID的验证)
      /^\d+$/.test(str)
  1.3 负整数的验证
      /^-\d+$/.test(str)
2、时间类
  2.1 短时间,形如 (13:04:06)
      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("时间格式不对");
          return false
        }
        return true;
      }
  2.2 短日期,形如 (2003-12-05)
      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]);
      }
  2.3 长时间,形如 (2003-12-05 13:04:06)
      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]);
      }
  2.4 只有年和月。形如(2003-05,或者2003-5)
  2.5 只有小时和分钟,形如(12:03)
3、表单类
  3.1 所有的表单的值都不能为空
      <input onblur="if(this.value.replace(/^\s+|\s+$/g,'')=='')alert('不能为空!')">
  3.2 多行文本框的值不能为空。
  3.3 多行文本框的值不能超过sMaxStrleng
  3.4 多行文本框的值不能少于sMixStrleng
  3.5 判断单选框是否选择。
  3.6 判断复选框是否选择.
  3.7 复选框的全选,多选,全不选,反选
  3.8 文件上传过程中判断文件类型
4、字符类
  4.1 判断字符全部由a-Z或者是A-Z的字字母组成
      <input onblur="if(/[^a-zA-Z]/g.test(this.value))alert('有错')">
  4.2 判断字符由字母和数字组成。
      <input onblur="if(/[^0-9a-zA-Z]/g.test(this.value))alert('有错')">
  4.3 判断字符由字母和数字,下划线,点号组成.且开头的只能是下划线和字母
      /^([a-zA-z_]{1})([\w]*)$/g.test(str)
  4.4 字符串替换函数.Replace();
5、浏览器类
  5.1 判断浏览器的类型
      window.navigator.appName
  5.2 判断ie的版本
      window.navigator.appVersion
  5.3 判断客户端的分辨率
      window.screen.height;  window.screen.width;
  
6、结合类
  6.1 email的判断。
      function ismail(mail)
      {
        return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)
[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(mail));
      }
  6.2 手机号码的验证
  6.3 身份证的验证
      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;
      }


3.7 复选框的全选,多选,全不选,反选
<form name=hrong>
<input type=checkbox name=All onclick="checkAll('mm')">全选<br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/><br/>


<input type=checkbox name=All2 onclick="checkAll('mm2')">全选<br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>

</form>

<SCRIPT LANGUAGE="javascript">
function checkAll(str)
{
  var a = document.getElementsByName(str);
  var n = a.length;
  for (var i=0; i<n; i++)
  a[i].checked = window.event.srcElement.checked;
}
function checkItem(str)
{
  var e = window.event.srcElement;
  var all = eval("document.hrong."+ str);
  if (e.checked)
  {
    var a = document.getElementsByName(e.name);
    all.checked = true;
    for (var i=0; i<a.length; i++)
    {
      if (!a[i].checked){ all.checked = false; break;}
    }
  }
  else all.checked = false;
}
</SCRIPT>

3.8 文件上传过程中判断文件类型
<input type=file onchange="alert(this.value.match(/^(.*)(\.)(.{1,8})$/)[3])">



不断地清空剪贴板:
<body onload="setInterval('clipboardData.setData(\'Text\',\'\')',100)">


<script language="javascript" type="text/javascript">
file://先复制一样东西,或者文本或者图片
if(clipboardData.getData("Text")||clipboardData.getData("HTML")||
clipboardData.getData("URL"))
{
alert("有效行为");
}
</script>
//保护页面不被打印、复制,禁止Mouse各键
<SCRIPT LANGUAGE="JavaScript">wside=(window.sidebar)?true:false;
var w456=false;
function nrcie(){return false;};
function nrcns(e) { if(e.which==2||e.which==3) return false;
}if(document.layers) { document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=nrcns;
}document.oncontextmenu=nrcie;
document.onselectstart=new Function("return false");
function nsel(){if((document.layers)||wside){var qwe= document.getSelection();
if(qwe!="") {window.find(" ")};
setTimeout("nsel()",20);
}}nsel();
function ccd(){clipboardData.clearData();
};
function cce(){ccd();
setTimeout("cce()",30);
};
cce();
</SCRIPT>

<style media='print'>body {display:none}</style>


页面上关于定位和长度的几个属性(原创)
首先是页面定位,用CSS

position,这个下面有两个属性absolute(绝对定位)和relative(相对定位),绝对定位是指相对浏览器的位置地位,而相对定位和其他元素的位置有关系,位置不固定。

以下可以看一个例子,看了之后就明白了

abc<br/>

<div style="position:relative;left:1;top:100;color:green">absolute positioning with the current element<br/><span style="position:absolute;left:0;top:0;">aaaaaaaaa</span></div>

<div style="color:red">absolute positioning with the body<br/><span style="position:absolute;left:0;top:0">bbbbbbbbbbb</span></div>

<div style="color:blue">relative positioning with the body<span style="position:relative;left:-12;top:0">ccccccccccc</span></div>

而有些CSS属性有时候需用position:absolute 之后才有效,比如裁切的那个CSS等

接下来是一些元素的位置问题

就拿宽度来说

scrollwidth,clientwidth,offsetwidth

这些属性都可以用在<body>,<div>等元素

第一个是包括滚动条所有在内的长度,第二个和第三个差不多,第三个是包括工具栏,菜单栏,状态栏,滚动条宽度等在内的宽度,而第二个是去掉一些cellpadding等一些的额外的宽度。高度同这个,元素分别为

scrollheight,clientheight,offsetheight

接下来是鼠标的位置

可以用event.clientX + document.body.scrollLeft得到横的绝对位置

这里面event.clientX 是相对屏幕的位置,而document.body.scrollLeft是网页被横向滚动条卷进去的宽度。

这里可以看一个例子,代码如下 把这个方法写在<body>的onmousemove中,一目了然了。

<SCRIPT>
<!--
function statusreport() {

  var tempx = event.clientX + document.body.scrollLeft;
  var tempy = event.clientY + document.body.scrollTop;
 
  window.status='在整个页面中的X, Y坐标 : ('+tempx+', '+tempy+') ; 在当前窗口中的X, Y坐标 : ( '+event.clientX+', '+event.clientY +')';
}
//-->

</SCRIPT>



大梅的思路,我把他用到了判断数据提交的时候有没有重复记录上了
<form name=form1>
<input name=a123>
<input name=b123>
<input name=c123>
<input name=d123>
<input name=e123>
<input name=f123 type=button onclick=check()>
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
Array.prototype.unique = function()
{
  var a = {}; for(var i=0; i<this.length; i++)
  {
    if(typeof a[this[i]] == "undefined")
      a[this[i]] = 1;
  }
  this.length = 0;
  for(var i in a)
    this[this.length] = i;
  return this;
}
function check()
{
var ArrText = [document.form1.a123.value,document.form1.b123.value,document.form1.c123.value,document.form1.d123.value,document.form1.e123.value];
OldArr=ArrText.length;
NewArr=ArrText.unique().length;
if(OldArr==NewArr)
{
alert("无重复记录");
}
else
{
alert("有重复记录");
}
}
//-->
</SCRIPT>

Date.prototype.Format = function(format)
{
  var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(),    //day
    "h+" : this.getHours(),   //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
    "S" : this.getMilliseconds() //millisecond
  }
  if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
    (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)if(new RegExp("("+ k +")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length==1 ? o[k] :
        ("00"+ o[k]).substr((""+ o[k]).length));
  return format;
};

示例:
alert(new Date().Format("yyyy年MM月dd日"));
alert(new Date().Format("MM/dd/yyyy"));
alert(new Date().Format("yyyyMMdd"));
alert(new Date().Format("yyyy-MM-dd hh:mm:ss"));

http://jkisjk.vip.sina.com/html/
空间已经过期
代码无法更新
示例仅提供思路:


常用前台JS函数

自动加上验证事件及日期按钮(htc方式)

自动加上验证事件及日期按钮(js方式)

Ctrl + 鼠标 = 选中(20050214)

固定Div(20050214)

可以盖住select的div(20041216)

可输入下拉框(20041126)(相似高亮显示,不相似移除)

可输入下拉框(20041126)(相似高亮显示,不相似不移除)

改变table的列宽(20041103)

可用鼠标移动和改变大小的table(20041029)

用鼠标移动TR(20050107)

固定Table首行(20041123)

固定Table首行首列(20041123)

Main Content Div

从服务器端取值并回填到页面

动态明细示例

多功能multiple-update

一个简单的IFRAME框架

调用客户端发邮件程序

读取客户端文件

一级选择左右移动及排库

二级选择左右移动

提交到特定大小的窗口

忠实显示Text内容(不同于Pre标签)

自动关闭Alert对话框

年月日选择


提交到特定大小的窗口

忠实显示Text内容(不同于Pre标签)

自动关闭Alert对话框

年月日选择


JS 对 cookie 操作
function setCookie(name,value)
{
  var Days = 30; //此 cookie 将被保存 30 天
  var exp  = new Date();    //new Date("December 31, 9998");
  exp.setTime(exp.getTime() + Days*24*60*60*1000);
  document.cookie = name + "="+ escape(value) +";expires="+ exp.toGMTString();
}
function getCookie(name)
{
  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  if(arr != null) return unescape(arr[2]); return null;
}
function delCookie(name)
{
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval=getCookie(name);
  if(cval!=null) document.cookie=name +"="+cval+";expires="+exp.toGMTString();
}


<script type="text/javascript">
var _st = window.setTimeout;

/*重载window.setTimeout函数,引用的函数可以带参数*/
window.setTimeout = function(fRef, mDelay) {
if(typeof fRef == 'function'){
  var argu = Array.prototype.slice.call(arguments,2);
alert(typeof(argu));
  var f = (function(){ fRef.apply(null, argu); });
  return _st(f, mDelay);
}
return _st(fRef,mDelay);
}

function test(x){
alert(x);
}
window.setTimeout(test,3000,'fason');
</script>


<script language=javascript>
<!--
/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)
function window.confirm(str)
{
    str=str.replace(/\'/g, "'&chr(39)&'").replace(/\r\n|\n|\r/g, "'&VBCrLf&'");
    execScript("n = msgbox('"+ str +"', 257, '自定的的 confirm')", "vbscript");
    return(n==1);
}
@end @*/
alert(confirm('sure?'));
// -->
</script>


//两端去空格函数
function trim(str) {
return str.replace(/(^\s*)|(\s*$)/g,"");
}


<script>
//为Number增加length方法
Number.prototype.length = function()
{
return String(this).length;
}

alert((11).length())
</script>

Ms XmlDom 异步装载Xml文件
放在这里,算作是资源备份吧。

<script>
var xmldoc;
function Load(){
  xmldoc = new ActiveXObject("Msxml2.DOMDocument");
  xmldoc.onreadystatechange = CheckState;
  xmldoc.resolveExternals = false;
  xmldoc.load(URL.value);
}
function CheckState(){
  var state = xmldoc.readyState;
  RESULTS.innerHTML += "加载状态 = " + state + "<BR>"
  if (state == 4){
    var err = xmldoc.parseError;
    if (err.errorCode != 0)
      RESULTS.innerHTML += err.reason +  "<BR>"
    else
    {
     RESULTS.innerHTML += "加载成功。" +  "<BR>"
     alert(xmldoc.xml)
     }
  }
}
</script>
URL: <input type=text size=60 id=URL value="http://dotnet.aspx.cc/Rss.aspx">
<input type=button value="正在XML" onclick="Load()">
<div id=RESULTS style="color:red; font-weight:bold;"></div></script>


//带中文字符串长度,一个中文字长度为2
String.prototype.lenB = function(){return this.replace(/[^\x00-\xff]/g,"**").length;}
document.all.tes1.value.lenB();



预判断一下链接URL是否可用

<script language="javascript">
function getURL(url)
{
    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.open("GET",url,false);
    xmlhttp.send();
    if (xmlhttp.readyState==4)
      alert((xmlhttp.Status==200)?"存在":"不存在");
}
//user like this:
getURL("http://localhost/1.asp")
</script>


//将数字转换成三位逗号分隔的样式
function formatNum(s)
{
  if(!/^(\+|-)?\d+(\.\d+)?$/.test(num)){alert("wrong!"); return num;}
  var re = new RegExp().compile("(file://d)(//d{3})(,|//.|$)");
  num += ""; while(re.test(num))
    num = num.replace(re, "$1,$2$3")
  return num;
}
alert(formatNum(-12345678.123));
alert(formatNum("12345678.123"));
alert(formatNum("10000000000000000000000000000000000000000"));



格式化日期:yyyy-m-d to yyyy-mm-dd

<SCRIPT LANGUAGE="JavaScript">
<!--
var str = "2005-3-2"; //2005-03-02
var str = "2005-3-22"; //2005-03-02
str = str.replace(/(\D)(\d)(?=\D|$)/g, "$10$2");
alert(str);
//-->
</SCRIPT>


表格中的行删除功能,用checkbox选择的
<script language="JavaScript">
<!--
var curRow=null;
function selectRow(tr1){
if(curRow)
curRow.bgColor="#FFFFFF";
tr1.bgColor="e7e7e7";
curRow=tr1;
}
function delTr(){
var chks=document.getElementsByName("chkDelete");
var tb=document.getElementById("tbContent");
for(var i=chks.length-1;i>=0;i--){
if(chks[i].checked){
tb.deleteRow(i);
}
}
}
//-->
</script>
<div align="center" style="overflow:auto; width:400; height:300px " id="divVector">
<table id="tbContent" border=1 width="300">
<script language="JavaScript">
<!--
for(var i=0;i<25;i++)
document.write('<tr height=20 onmouseover="selectRow(this)"><td algin="center"

width="20%"><input type="checkbox" name="chkDelete"></td><td width="80%"

align="center">'+i+'</td></tr>');
//-->
</script>
</table>
</div>
<input type="button" value=" 删除选中的行 " onclick="delTr()">


yyyy-mm-dd格式日期完整校验加提示
<script language="JavaScript">
<!--
function CheckDate(strDate){
var reg=/^(\d{4})([-])(\d{2})([-])(\d{2})/;
if(!reg.test(strDate)){
alert("日期格式不正确!\n正确格式为:2004-01-01");
return false;
}
var ss=strDate.split("-");
var year=ss[0];
var month=ss[1];
var date=ss[2];
if(!checkYear(year)){return false;}
if(!checkMonth(month)){return false;}
if(!checkDate(year,month,date)){return false;}
return true;
}
function checkYear(year){
if(isNaN(parseInt(year))){alert("年份输入有误,请重新输入!"); return false;}
else if(parseInt(year)<1950 || parseInt(year) >2050){ alert("年份应该在1950-2050之间

!"); return false}
else return true;
}
function checkMonth(month){
if(isNaN(parseInt(month))){alert("月份输入有误,请重新输入!"); return false;}
else if(parseInt(month)<1 || parseInt(month) >12){ alert("月份应该在1-12之间!");

return false}
else return true;
}
function checkDate(year,month,date){
var daysOfMonth=CalDays(parseInt(year),parseInt(month));
if(isNaN(parseInt(date))){alert("日期输入有误,请重新输入!"); return false;}
else if(parseInt(date)<0||parseInt(date)>daysOfMonth){ alert("日期应该在1

-"+daysOfMonth+"之间!"); return false;}
else return true;
}
function CalDays(year,month){
var date= new Date(year,month,0);
return date.getDate();
}
function isLeapYear(year){
if((year %4==0 && year %100!=0) || (year %400==0)) return true;
else return false;
}
alert(CheckDate("2007-02-29"));
//-->
</script>


<script language="JavaScript">
<!--
/* 函数名称 : dateAfterDays
* 函数功能 : 返回与某日期相距N天(N个24小时)的日期
* 函数参数 : num number类型 可以为正负整数或者浮点数
* 函数返回 : 新的日期
* 调用方法 : dateObject.dateAfterDays(num);
*/
Date.prototype.dateAfterDays=function(num){
if(typeof(num)!="number") throw new Error("Date(num)参数为数值类型.",-1);
var date = this.valueOf();
date += num*24*3600*1000;
return new Date(date);
}
var dd= new Date();
alert(dd.dateAfterDays(1.5));
//-->
</script>


类似CSDN感兴趣社区配置页面中的checkbox选择的功能
<script language="JavaScript">
<!--
function chkClk(obj){
var chks=document.getElementsByName(obj.name);
if(obj.flag=="main"){
for(var i=1;i<chks.length;i++)
chks[i].checked=obj.checked;
}
else{
for(var i=1;i<chks.length;i++)
if(chks[i].checked==false){
chks[0].checked=false;
break;
}
else{
if(i==chks.length-1) chks[0].checked=true;
}
}
}
//-->
</script>

<input type="checkbox" onclick="chkClk(this)" name="type1" flag="main">typetext
<li><input type="checkbox" onclick="chkClk(this)" name="type1">typetext</li>
<li><input type="checkbox" onclick="chkClk(this)" name="type1">typetext</li>
<br/><br/>
<input type="checkbox" onclick="chkClk(this)" name="type2" flag="main">typetext
<li><input type="checkbox" onclick="chkClk(this)" name="type2">typetext</li>
<li><input type="checkbox" onclick="chkClk(this)" name="type2">typetext</li>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics