首页 > 编程 > JS > 正文

网页教学网整理的JS技巧代码

2020-09-19 11:12:15
字体:
来源:转载
供稿:网友

相关文章:网页设计整理的javascript的技巧代码

//过滤数字

<input type=text onkeypress="return event.keycode>=48&&event.keycode<=57||(this.value.indexof('.')<0?event.keycode==46:false)" onpaste="return !clipboarddata.getdata('text').match(//d/)" ondragenter="return false">

//特殊用途

<input type=button value=导入收藏夹 onclick="window.external.importexportfavorites(true,'http://localhost');">
<input type=button value=导出收藏夹 onclick="window.external.importexportfavorites(false,'http://localhost');">
<input type=button value=整理收藏夹 onclick="window.external.showbrowserui('organizefavorites', null)">
<input type=button value=语言设置   onclick="window.external.showbrowserui('languagedialog', null)">
<input type=button value=加入收藏夹 onclick="window.external.addfavorite('http://www.google.com/', 'google')">
<input type=button value=加入到频道 onclick="window.external.addchannel('http://www.google.com/')">
<input type=button value=加入到频道 onclick="window.external.showbrowserui('privacysettings',null)">

//不缓存

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache, must-revalidate">
<meta http-equiv="expires" content="0">

//正则匹配

匹配中文字符的正则表达式: [/u4e00-/u9fa5]
匹配双字节字符(包括汉字在内):[^/x00-/xff]
匹配空行的正则表达式:/n[/s| ]*/r
匹配html标记的正则表达式:/<(.*)>.*<///1>|<(.*) //>/ 
匹配首尾空格的正则表达式:(^/s*)|(/s*$)(像vbscript那样的trim函数)
匹配email地址的正则表达式:/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*
匹配网址url的正则表达式:http://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?

以下是例子:

利用正则表达式限制网页表单里的文本框输入内容:

用正则表达式限制只能输入中文:onkeyup="value=value.replace(/[^/u4e00-/u9fa5]/g,'')" onbeforepaste="clipboarddata.setdata('text',clipboarddata.getdata('text').replace(/[^/u4e00-/u9fa5]/g,''))"
1.用正则表达式限制只能输入全角字符: onkeyup="value=value.replace(/[^/uff00-/uffff]/g,'')" onbeforepaste="clipboarddata.setdata('text',clipboarddata.getdata('text').replace(/[^/uff00-/uffff]/g,''))"
2.用正则表达式限制只能输入数字:onkeyup="value=value.replace(/[^/d]/g,'') "onbeforepaste="clipboarddata.setdata('text',clipboarddata.getdata('text').replace(/[^/d]/g,''))"
3.用正则表达式限制只能输入数字和英文:onkeyup="value=value.replace(/[/w]/g,'') "onbeforepaste="clipboarddata.setdata('text',clipboarddata.getdata('text').replace(/[^/d]/g,''))"

//消除图像工具栏

<img src="mypicture.jpg" height="100px" width="100px" galleryimg="false"> 
or
<head>
<meta http-equiv="imagetoolbar" content="no">
</head>

//无提示关闭

function close()
{
var ua=navigator.useragent
var ie=navigator.appname=="microsoft internet explorer"?true:false
if(ie)
{
      var ieversion=parsefloat(ua.substring(ua.indexof("msie ")+5,ua.indexof(";",ua.indexof("msie "))))
  if(ieversion< 5.5)
  {
   var str  = '<object id=notipclose classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11">'
       str += '<param name="command" value="close"></object>';
       document.body.insertadjacenthtml("beforeend", str);
       document.all.notipclose.click();
  }
      else
  {
       window.opener =null;
       window.close();
      }
   }
else
{
  window.close()
   }
}

//取得控件得绝对位置(1)

<script language="javascript"> 
function getoffset(e)

 var t=e.offsettop; 
 var l=e.offsetleft; 
 while(e=e.offsetparent)
 { 
  t+=e.offsettop; 
  l+=e.offsetleft; 
 } 
 var rec = new array(1);
 rec[0]  = t;
 rec[1] = l;
 return rec

</script>

//获得控件的绝对位置(2)

orect = obj.getboundingclientrect();
orect.left
orect.

//最小化,最大化,关闭

<object id=min classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11"> 
<param name="command" value="minimize"></object> 
<object id=max classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11"> 
<param name="command" value="maximize"></object> 
<object id=close classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11"> 
<param name="command" value="close"></object> 
<input type=button value=最小化 onclick=min.click()> 
<input type=button value=最大化 onclick=max.click()> 
<input type=button value=关闭 onclick=close.click()> 

//光标停在文字最后

<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()">

//页面进入和退出的特效


进入页面<meta http-equiv="page-enter" content="revealtrans(duration=x, transition=y)">
推出页面<meta http-equiv="page-exit" content="revealtrans(duration=x, transition=y)"> 
这个是页面被载入和调出时的一些特效。duration表示特效的持续时间,以秒为单位。transition表示使
用哪种特效,取值为1-23:
  0 矩形缩小 
  1 矩形扩大 
  2 圆形缩小
  3 圆形扩大 
  4 下到上刷新 
  5 上到下刷新
  6 左到右刷新 
  7 右到左刷新 
  8 竖百叶窗
  9 横百叶窗 
  10 错位横百叶窗 
  11 错位竖百叶窗
  12 点扩散 
  13 左右到中间刷新 
  14 中间到左右刷新
  15 中间到上下
  16 上下到中间 
  17 右下到左上
  18 右上到左下 
  19 左上到右下 
  20 左下到右上
  21 横条 
  22 竖条 
  23 

//网页是否被检索

<meta name="robots" content="属性值">
  其中属性值有以下一些:
  属性值为"all": 文件将被检索,且页上链接可被查询;
  属性值为"none": 文件不被检索,而且不查询页上的链接;
  属性值为"index": 文件将被检索;
  属性值为"follow": 查询页上的链接;
  属性值为"noindex": 文件不检索,但可被查询链接;
  属性值为"nofollow": 

//打印分页

<p  style="page-break-after:always">page1</p>  
<p  style="page-break-after:always">page2</p>  

//设置打印

 
<object id="factory" style="display:none" viewastext
  classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"
  codebase="http://www.meadroid.com/scriptx/scriptx.cab#version=5,60,0,360"
></object>
<input type=button value=页面设置 onclick="factory.printing.pagesetup()">
<input type=button value=打印预览 onclick="factory.printing.preview()">
 
<script language=javascript>
function window.onload()
{
   // -- advanced features
   factory.printing.setmarginmeasure(2) // measure margins in inches
   factory.printing.setpagerange(false, 1, 3) // need pages from 1 to 3
   factory.printing.printer = "hp deskjet 870c"
   factory.printing.copies = 2
   factory.printing.collate = true
   factory.printing.papersize = "a4"
   factory.printing.papersource = "manual feed"
   // -- basic features
   factory.printing.header = "居左显示&b居中显示&b居右显示页码,第&p页/共&p页"
   factory.printing.footer = "(自定义页脚)"
   factory.printing.portrait = false
   factory.printing.leftmargin = 0.75
   factory.printing.topmargin = 1.5
   factory.printing.rightmargin = 0.75
   factory.printing.bottommargin = 1.5
}
function print(frame) {
  factory.printing.print(true, frame) // print with prompt
}
</script>
<input type=button value="打印本页" onclick="factory.printing.print(false)">
<input type=button value="页面设置" onclick="factory.printing.pagesetup()">
<input type=button value="打印预览" onclick="factory.printing.preview()"><br>
<a href="http://www.meadroid.com/scriptx/docs/printdoc.htm?static"  target=_blank>具体使用手册,更多信息,点这里</a>

//自带的打印预览

webbrowser.execwb(1,1) 打开 
web.execwb(2,1) 关闭现在所有的ie窗口,并打开一个新窗口 
web.execwb(4,1) 保存网页 
web.execwb(6,1) 打印 
web.execwb(7,1) 打印预览 
web.execwb(8,1) 打印页面设置 
web.execwb(10,1) 查看页面属性 
web.execwb(15,1) 好像是撤销,有待确认 
web.execwb(17,1) 全选 
web.execwb(22,1) 刷新 
web.execwb(45,1) 关闭窗体无提示 
<style media=print> 
.noprint{display:none;}<!--用本样式在打印时隐藏非打印项目--> 
.pagenext{page-break-after: always;}<!--控制分页--> 
</style> 
<object  id="webbrowser"  width=0  height=0  classid="clsid:8856f961-340a-11d0-a96b-00c04fd705a2">    
</object>
<center class="noprint" >
<input type=button value=打印 onclick=document.all.webbrowser.execwb(6,1)> 
<input type=button value=直接打印 onclick=document.all.webbrowser.execwb(6,6)> 
<input type=button value=页面设置 onclick=document.all.webbrowser.execwb(8,1)> 
</p> 
<p> <input type=button value=打印预览 onclick=document.all.webbrowser.execwb(7,1)> 
</center>

//去掉打印时的页眉页脚

 
<script  language="javascript">  
var hkey_root,hkey_path,hkey_key;
hkey_root="hkey_current_user";
hkey_path="//software//microsoft//internet explorer//pagesetup//";
//设置网页打印的页眉页脚为空
function pagesetup_null()
{
 try
 {
         var wsh=new activexobject("wscript.shell");
  hkey_key="header";
  wsh.regwrite(hkey_root+hkey_path+hkey_key,"");
  hkey_key="footer";
  wsh.regwrite(hkey_root+hkey_path+hkey_key,"");
 }
 catch(e){}
}
//设置网页打印的页眉页脚为默认值
function  pagesetup_default()
{  
 try
 {
  var wsh=new activexobject("wscript.shell");
  hkey_key="header";
  wsh.regwrite(hkey_root+hkey_path+hkey_key,"&w&b页码,&p/&p");
  hkey_key="footer";
  wsh.regwrite(hkey_root+hkey_path+hkey_key,"&u&b&d");
 }
 catch(e){}
}
</script>
<input type="button" value="清空页码" onclick=pagesetup_null()>
<input type="button" value="恢复页码" onclick=pagesetup_default()>

//浏览器验证

function checkbrowser()

   this.ver=navigator.appversion 
   this.dom=document.getelementbyid?1:0 
   this.ie6=(this.ver.indexof("msie 6")>-1 && this.dom)?1:0; 
   this.ie5=(this.ver.indexof("msie 5")>-1 && this.dom)?1:0; 
   this.ie4=(document.all && !this.dom)?1:0; 
   this.ns5=(this.dom && parseint(this.ver) >= 5) ?1:0; 
   this.ns4=(document.layers && !this.dom)?1:0; 
   this.mac=(this.ver.indexof('mac') > -1) ?1:0; 
   this.ope=(navigator.useragent.indexof('opera')>-1); 
   this.ie=(this.ie6 || this.ie5 || this.ie4) 
   this.ns=(this.ns4 || this.ns5) 
   this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns5 || this.ns4 || this.mac || this.ope) 
   this.nbw=(!this.bw) 
   return this;
}

//计算内容宽和高

<script  language="javascript">  
function  test(obj)  
{  
       var  range  =  obj.createtextrange();  
       alert("内容区宽度:  "  +  range.boundingwidth    
                                                 +  "px/r/n内容区高度:  "  +  range.boundingheight  +  "px");  
             
}  
</script>  
<body>  
<textarea id="txt" height="150">sdf</textarea><input  type="button"  value="计算内容宽度"  onclick="test(txt)">  
</body>

//无模式的提示框

function modelessalert(msg)
{
   window.showmodelessdialog("javascript:alert(/""+escape(msg)+"/");window.close();","","status:no;resizable:no;help:no;dialogheight:height:30px;dialogheight:40px;");
}

//屏蔽按键

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=gb2312">
  <noscript><meta http-equiv="refresh" content="0;url=about:noscript"></noscript>
  <title>屏蔽鼠标右键、ctrl+n、shift+f10、alt+f4、f11、f5刷新、退格键</title>
</head>
<body>
<script language="javascript"><!--
  //屏蔽鼠标右键、ctrl+n、shift+f10、f11、f5刷新、退格键
  //author: meizz(梅花雨) 2002-6-18
function document.oncontextmenu(){event.returnvalue=false;}//屏蔽鼠标右键
function window.onhelp(){return false} //屏蔽f1帮助
function document.onkeydown()
{
  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.keycode==116)||                 //屏蔽 f5 刷新键
      (event.ctrlkey && event.keycode==82)){ //ctrl + r
     event.keycode=0;
     event.returnvalue=false;
     }
  if (event.keycode==122){event.keycode=0;event.returnvalue=false;}  //屏蔽f11
  if (event.ctrlkey && event.keycode==78) event.returnvalue=false;   //屏蔽 ctrl+n
  if (event.shiftkey && event.keycode==121)event.returnvalue=false;  //屏蔽 shift+f10
  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;
  }
}
</script>
屏蔽鼠标右键、ctrl+n、shift+f10、alt+f4、f11、f5刷新、退格键
</body>
</html>

//屏蔽打印

<style>
@media print{
* {display:none}
}
</style>

//移动的图层,拖动

1.

<span style='position:absolute;width:200;height:200;background:red' onmousedown=mousedown(this) onmousemove=mousemove() onmouseup=mouseup()>meizz</span>
<script language=javascript>
var obj;
function mousedown(obj)
{
  obj=obj;
  obj.setcapture();
  obj.l=event.x-obj.style.pixelleft;
  obj.t=event.y-obj.style.pixeltop;
}
function mousemove()
{
  if(obj!=null)
  {
    obj.style.left = event.x-obj.l;
    obj.style.top = event.y-obj.t;
  }
}
function mouseup()
{
  if(obj!=null)
  {
    obj.releasecapture();
    obj=null;
  }
}
</script>

2.
<div id="mydiv" src="logo.gif" ondrag="dodrag();" onmouseover="this.style.cursor='hand'" style="position:absolute;left=100;top=100;" onmousedown="domousedown();">
<a href="#" onclick="return false"><h1>wlecome</h1></a>
</div>
<script language="javascript" type="text/javascript">
var orgmousex;
var orgmousey;
var orgobjx;
var orgobjy;
function dodrag()
{
var myobject=document.all.mydiv;
var x=event.clientx;
var y=event.clienty;
myobject.style.left=x-(orgmousex-orgobjx);
myobject.style.top=y-(orgmousey-orgobjy);
 
}
function domousedown()
{
orgmousex=event.clientx;
orgmousey=event.clienty;
orgobjx=parseint(document.all.mydiv.style.left);
orgobjy=parseint(document.all.mydiv.style.top);
}
</script>


//文档状态改变

<iframe src="a.html" id="f" name="f" scrolling="no" frameborder=0 marginwidth=0 marginheight=0></iframe>
<script>
var doc=window.frames["f"].document;
function s(){
 if (doc.readystate=="complete"){
  document.all.f.style.height=doc.body.scrollheight
  document.all.f.style.width=doc.body.scrollwidth
 }
}
doc.onreadystatechange=s
</script>


//刷新后不变的文本框

<html>
<head>
<meta name="save" content="history">
<style>
   .shistory {behavior:url(#default#savehistory);}
</style>
</head>
<body>
<input class=shistory type=text id=opersistinput>
</body>
</html>


//访问剪贴板

(1)拖拽访问

event.datatransfer.setdata("url", oimage.src);
simageurl = event.datatransfer.getdata("url");

(2)普通访问

window.clipboarddata.setdata("text",osource.innertext);
window.clipboarddata.getdata("text");

//操作cookie

function setcookie(sname, svalue)
{
document.cookie = sname + "=" + escape(svalue) + "; ";
}
function getcookie(sname)
{
var acookie = document.cookie.split("; ");
for (var i=0; i < acookie.length; i++)
{
  
  var acrumb = acookie[i].split("=");
  if (sname == acrumb[0]) 
  return unescape(acrumb[1]);
}
 
}
function delcookie(sname)
{
document.cookie = sname + "=" + escape(svalue) + "; expires=fri, 31 dec 1999 23:59:59 gmt;";
}

//settimeout增加参数

<script>
var _st = window.settimeout;
window.settimeout = function(fref, mdelay) {
 if(typeof fref == 'function'){
  var argu = array.prototype.slice.call(arguments,2);
  var f = (function(){ fref.apply(null, argu); });
  return _st(f, mdelay);
 }
 return _st(fref,mdelay);
}
function test(x){
 alert(x);
}
window.settimeout(test,1000,'fason');
</script>

//自定义的apply,call

function.prototype.apply = function (obj, argu) {
if (obj) obj.constructor.prototype._caller = this; 
var argus = new array();
for (var i=0;i<argu.length;i++)
  argus[i] = "argu[" + i + "]";
var r;
eval("r = " + (obj ? ("obj._caller(" + argus.join(",") + ");") : ("this(" + argus.join(",") + ");")));
return r;
};
function.prototype.call = function (obj) {
var argu = new array();
for (var i=1;i<arguments.length;i++)
  argu[i-1] = arguments[i];
return this.apply(obj, argu);
};

//下载文件

function downurl(strremoteurl,strlocalurl)
{
try
{
  var xmlhttp=new activexobject("microsoft.xmlhttp");
  xmlhttp.open("get",strremoteurl,false);
  xmlhttp.send();
  var adodbstream=new activexobject("adodb.stream");
  adodbstream.type=1;//1=adtypebinary
  adodbstream.open();
  adodbstream.write(xmlhttp.responsebody);
  adodbstream.savetofile(strlocalurl,2);
  adodbstream.close();
  adodbstream=null;
  xmlhttp=null;
  
}
catch(e)
{
  window.confirm("下载url出错!");
}
//window.confirm("下载完成.");
}

//检验连接是否有效

function getxml(url) 
{
var xmlhttp = new activexobject("microsoft.xmlhttp");
xmlhttp.open("get",url, false); 
try

  xmlhttp.send();
}
catch(e){}
finally 
{
  var result = xmlhttp.responsetext;
  if(result) 
  {
   if(xmlhttp.status==200)
   {
    return(true);
   }
   else 
   {
    return(false);
   }
  }
  else 
  {
   return(false);
  }
}
}

//post代替form

<script language="vbscript">
function urlencoding(vstrin)
    strreturn = ""
    for i = 1 to len(vstrin)
        thischr = mid(vstrin,i,1)
        if abs(asc(thischr)) < &hff then
            strreturn = strreturn & thischr
        else
            innercode = asc(thischr)
            if innercode < 0 then
                innercode = innercode + &h10000
            end if
            hight8 = (innercode  and &hff00)/ &hff
            low8 = innercode and &hff
            strreturn = strreturn & "%" & hex(hight8) &  "%" & hex(low8)
        end if
    next
    urlencoding = strreturn
end function
function bytes2bstr(vin)
    strreturn = ""
    for i = 1 to lenb(vin)
        thischarcode = ascb(midb(vin,i,1))
        if thischarcode < &h80 then
            strreturn = strreturn & chr(thischarcode)
        else
            nextcharcode = ascb(midb(vin,i+1,1))
            strreturn = strreturn & chr(clng(thischarcode) * &h100 + cint(nextcharcode))
            i = i + 1
        end if
    next
    bytes2bstr = strreturn
end function
dim stra,oreq
stra = urlencoding("submit1=submit&text1=中文")
set oreq = createobject("msxml2.xmlhttp")
oreq.open "post","http://servername/vdir/tstresult.asp",false
oreq.setrequestheader "content-length",len(stra)
oreq.setrequestheader "content-type","application/x-www-form-urlencoded"
oreq.send stra
msgbox bytes2bstr(oreq.responsebody)
</script>

//readystate是xmlhttp返回数据的进度,0=载入中,1=未初始化,2=已载入,3=运行中,4=完成

//组件是否安装

iscomponentinstalled("{6b053a4b-a7ec-4d3d-4567-b8ff8a1a5739}", "componentid"))

//检查网页是否存在

function checkurl(url)
{
  var xmlhttp = new activexobject("microsoft.xmlhttp");
  xmlhttp.open("get",url, false);
  try
  { 
    xmlhttp.send(); 
    var result = xmlhttp.status;
  }
  catch(e) {return(false); }
  if(result==200)
  { 
    return true;
  }
  xmlhttp = null;
  return false;
}

//连接数据库

<script language="javascript">
  //用 javascript 写服务器端连接数据库的代码示例
  var conn = new activexobject("adodb.connection");
  conn.open("provider=sqloledb.1; data source=localhost; user id=sa; "
    +"password=; initial catalog=pubs");
  var rs = new activexobject("adodb.recordset");
  var sql="select * from authors";
  rs.open(sql, conn);
 shtml = "<table width='100%' border=1>";
 shtml +="<tr bgcolor='#f4f4f4'><td>au_id</td><td>au_lname</td><td>au_fname</td><td>phone</td><td>address</td><td> city</td><td>state</td><td>zip</td></tr>";
  while(!rs.eof)
  {
 shtml += "<tr><td>" + rs("au_id") + "</td><td>" + rs("au_lname") + "</td><td>" + rs("au_fname") + "</td><td>" + rs("phone") + "</td><td>" + rs("address") + "</td><td>" + rs("city") + "</td><td>" + rs("state") + "</td><td>" + rs("zip") + "</td></tr>";
 rs.movenext;
  }
  shtml += "</table>";
  document.write(shtml);
  rs.close(); 
  rs = null; 
  conn.close(); 
  conn = null;
</script>

//使用数据岛

<html>
<body>
srno:<input type=text datasrc=#xmldate datafld=srno size="76"><br>
times:<input type=text datasrc=#xmldate datafld=times size="76"><br>
<input id="first" type=button value="<< 第一条记录" onclick="xmldate.recordset.movefirst()">
<input id="prev" type=button value="<上一条记录" onclick="xmldate.recordset.moveprevious()">  
<input id="next" type=button value="下一条记录>" onclick="xmldate.recordset.movenext()">  
<input id="last" type=button value="最后一条记录>>" onclick="xmldate.recordset.movelast()">   
<input id="add" type=button value="添加新记录" onclick="xmldate.recordset.addnew()">  
<xml id="xmldate">
<infolist>
<info ><srno>20041025-01</srno><times>null</times></info>
<info ><srno>20041101-09</srno><times>2004年10月1日2点22分0秒</times></info>
</infolist>
</xml>
</body>
</html>

//获得参数

<body>
<a href="javascript:location.href=location.href + '?a=1&b=2'">search</a>
<script language="javascript">
<!--
var a = location.search.substr(1);
if(a.length>0)
{
 var re = /([^&]*?)/=([^&]*)/g
 var s = a.match(re);
 for(var i= 0;i<s.length;i++)
 {
  alert(s[i]);
  alert(s[i].split("=")[1]);
 }
}
//-->
</script>
</body>

//可编辑select

<input type=text name=re_name style="width:100px;height:21px;font-size:10pt;"><span style="width:18px;border:0px solid red;"><select name="r00" style="margin-left:-100px;width:118px; background-color:#ffeeee;" onchange="document.all.re_name.value=this.value;">
                <option value="1">11111111<option>
                <option value="2">222222</option>
                <option value="3">333333</option>
              </select>
              </span>


//设置光标位置

function getcaret(textbox)
{
var control = document.activeelement;
textbox.focus();
var rang = document.selection.createrange();
  rang.setendpoint("starttostart",textbox.createtextrange())
control.focus();
return rang.text.length;
}
function setcaret(textbox,pos)
{
try
{
  var r =textbox.createtextrange();
   r.movestart('character',pos);
   r.collapse(true);
   r.select();
}
catch(e)
{}
}
function selectlength(textbox,start,len)
{
try
{
  var r =textbox.createtextrange();
 
  r.moveend('character',len-(textbox.value.length-start));
  r.movestart('character',start);
  
  r.select();
}
catch(e)
{//alert(e.description)}
}
function insertatcaret(textbox,text)
{
textbox.focus();
document.selection.createrange().text = text;
}

//页内查找

function findinpage(str)
{
var txt, i, found,n = 0;
if (str == "")
{
  return false;
}
txt = document.body.createtextrange();
for (i = 0; i <= n && (found = txt.findtext(str)) != false; i++)
{
  txt.movestart("character", 1);
  txt.moveend("textedit");
}
if (found)
{
  txt.movestart("character", -1);
  txt.findtext(str);
  txt.select();
  txt.scrollintoview();
  n++;  
}
else
{
  if (n > 0)
  {
   n = 0;
   findinpage(str);
  }
  else
  {
   alert(str + "...            您要找的文字不存在。/n /n请试着输入页面中的关键字再次查找!");
  }
}
return false;
}

//操作execl

<script language="javascript">
function jstartexcel() {
 var xls = new activexobject ( "excel.application" );
 xls.visible = true;
 var newbook = xls.workbooks.add;
 newbook.worksheets.add;
 newbook.worksheets(1).activate;
 xls.activeworkbook.activesheet.pagesetup.orientation = 2;
 xls.activeworkbook.activesheet.pagesetup.papersize = 5;
 newbook.worksheets(1).columns("a").columnwidth=50;
 newbook.worksheets(1).columns("a").wraptext = true;
 newbook.worksheets(1).columns("b").columnwidth=50;
 newbook.worksheets(1).columns("b").wraptext = true;
 newbook.worksheets(1).range("a1:b1000").numberformat = "0";
 newbook.worksheets(1).range("a1:b1000").horizontalalignment = -4131;
 newbook.worksheets(1).cells(1,1).interior.colorindex="15";
 newbook.worksheets(1).cells(1,1).value="first column, first cell";
 newbook.worksheets(1).cells(2,1).value="first column, second cell";
 newbook.worksheets(1).cells(1,2).value="second column, first cell";
 newbook.worksheets(1).cells(2,2).value="second column, second cell";
 newbook.worksheets(1).name="my first worksheet";
}
</script>

//自定义提示条

<a href="#" title="这是提示">tip</a>
<script language="javascript">
//***********默认设置定义.*********************
tpopwait=50;//停留twait豪秒后显示提示。
tpopshow=5000;//显示tshow豪秒后关闭提示
showpopstep=20;
popopacity=99;
//***************内部变量定义*****************
spop=null;
curshow=null;
tfadeout=null;
tfadein=null;
tfadewaiting=null;
document.write("<style type='text/css'id='defaultpopstyle'>");
document.write(".cpoptext {  background-color: #f8f8f5;color:#000000; border: 1px #000000 solid;font-color: font-size: 12px; padding-right: 4px; padding-left: 4px; height: 20px; padding-top: 2px; padding-bottom: 2px; filter: alpha(opacity=0)}");
document.write("</style>");
document.write("<div id='dypoplayer' style='position:absolute;z-index:1000;' class='cpoptext'></div>");
function showpopuptext(){
var o=event.srcelement;
mousex=event.x;
mousey=event.y;
if(o.alt!=null && o.alt!=""){o.dypop=o.alt;o.alt=""};
        if(o.title!=null && o.title!=""){o.dypop=o.title;o.title=""};
if(o.dypop!=spop) {
spop=o.dypop;
cleartimeout(curshow);
cleartimeout(tfadeout);
cleartimeout(tfadein);
cleartimeout(tfadewaiting);
if(spop==null || spop=="") {
dypoplayer.innerhtml="";
dypoplayer.style.filter="alpha()";
dypoplayer.filters.alpha.opacity=0;
}
else {
if(o.dyclass!=null) popstyle=o.dyclass 
else popstyle="cpoptext";
curshow=settimeout("showit()",tpopwait);
}
}
}
function showit(){
dypoplayer.classname=popstyle;
dypoplayer.innerhtml=spop;
popwidth=dypoplayer.clientwidth;
popheight=dypoplayer.clientheight;
if(mousex+12+popwidth>document.body.clientwidth) popleftadjust=-popwidth-24
else popleftadjust=0;
if(mousey+12+popheight>document.body.clientheight) poptopadjust=-popheight-24
else poptopadjust=0;
dypoplayer.style.left=mousex+12+document.body.scrollleft+popleftadjust;
dypoplayer.style.top=mousey+12+document.body.scrolltop+poptopadjust;
dypoplayer.style.filter="alpha(opacity=0)";
fadeout();
}
function fadeout(){
if(dypoplayer.filters.alpha.opacity<popopacity) {
dypoplayer.filters.alpha.opacity+=showpopstep;
tfadeout=settimeout("fadeout()",1);
}
else {
dypoplayer.filters.alpha.opacity=popopacity;
tfadewaiting=settimeout("fadein()",tpopshow);
}
}
function fadein(){
if(dypoplayer.filters.alpha.opacity>0) {
dypoplayer.filters.alpha.opacity-=1;
tfadein=settimeout("fadein()",1);
}
}
document.onmouseover=showpopuptext;
</script>


//插入文字

document.onclick =function(){ 
var osource = window.event.srcelement; 
if(osource.tagname!="div") 
return false; 
var sel = document.selection; 
if (sel!=null) { 
var rng = sel.createrange(); 
if (rng!=null) 
rng.pastehtml("<font color=red>插入文字</font>"); 


//netscapte下操作xml
doc = new activexobject("msxml2.domdocument");
doc = new activexobject("microsoft.xmldom")
->>
doc = (new domparser()).parsefromstring(sxml,'text/xml')

//判断键值

<html>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<head>
<script language="javascript">
var ie  =navigator.appname=="microsoft internet explorer"?true:false;
  
function keydown(e)
{
 if(!ie)
 {
  var nkey=e.which;
  var iekey='现在是ns浏览器';
  var realkey=string.fromcharcode(e.which);
 }
 if(ie)
 {
  var iekey=event.keycode;
  var nkey='现在是ie浏览器';
  var realkey=string.fromcharcode(event.keycode);
  if(event.keycode==32){realkey='/' 空格/''}
  if(event.keycode==13){realkey='/' 回车/''}
  if(event.keycode==27){realkey='/' esc/''}
  if(event.keycode==16){realkey='/' shift/''}
  if(event.keycode==17){realkey='/' ctrl/''}
  if(event.keycode==18){realkey='/' alt/''}
 }
 alert('ns浏览器中键值:'+nkey+'/n'+'ie浏览器中键值:'+iekey+'/n'+'实际键为'+realkey);
}
document.onkeydown = keydown;
</script>
</head>
<body>
//javascript document.
<hr>
<center>
<h3>请按任意一个键。。。。</h3>
</center>
</body>
</html>

//禁止fso


1.注销组件
regsvr32 /u scrrun.dll
2.修改progid 
hkey_classes_root/scripting.filesystemobject
scripting.filesystemobject
3.对于使用object的用户,修改hkey_classes_root/scripting.

//省略号

<div style="width: 120px; height: 50px; border: 1px solid blue;
            overflow: hidden; text-overflow:ellipsis">
<nobr>就是比如有一行文字,很长,表格内一行显示不下.</nobr>
</div>

//检测media play版本

<ie:clientcaps id="oclientcaps" style="{behavior:url(#default#clientcaps)}" />
<script>
var flash="";
    wmpversion= oclientcaps.getcomponentversion("{22d6f312-b0f6-11d0-94ab-0080c74c7e95}","componentid"); 
    if (wmpversion != "") {
    flash = "";
    var version = wmpversion.split(",");
    var i;
    for (i = 0; i < version.length; i++) {
      if (i != 0)
    flash += ".";
      flash += version[i];
    }
     document.write("您的windows media player 版本是:"+flash+"<p>");
  }
</script>

//图象按比例

<script language="javascript">
<!--
//图片按比例缩放
var flag=false;
function drawimage(imgd){
 var image=new image();
 var iwidth = 80;  //定义允许图片宽度
 var iheight = 80;  //定义允许图片高度
 image.src=imgd.src;
 if(image.width>0 && image.height>0){
 flag=true;
 if(image.width/image.height>= iwidth/iheight){
  if(image.width>iwidth){  
  imgd.width=iwidth;
  imgd.height=(image.height*iwidth)/image.width;
  }else{
  imgd.width=image.width;  
  imgd.height=image.height;
  }
  imgd.alt=image.width+"&#215;"+image.height;
  }
 else{
  if(image.height>iheight){  
  imgd.height=iheight;
  imgd.width=(image.width*iheight)/image.height;  
  }else{
  imgd.width=image.width;  
  imgd.height=image.height;
  }
  imgd.alt=image.width+"&#215;"+image.height;
  }
 }

//-->
</script>
<img src=".." onload = "drawimage(this)">

//细线select

<span style="border:1px solid #000000; position:absolute; overflow:hidden;" >
<select style="margin:-2px;">
<option>1111</option>
<option>11111111111111</option>
<option>111111111</option>
</select></span>

//import

function import() {
for( var i=0; i<arguments.length; i++ ) {
  var file = arguments[i];
  if ( file.match(//.js$/i)) 
   document.write('<script type=/"text/javascript/" src=/"' + file + '/"></sc' + 'ript>');
  else
   document.write('<style type=/"text/css/">@import /"' + file + '/" ;</style>');
}
};


//js枚举

function getcomputername()
{
var objwmiservice = getobject("winmgmts:root/cimv2");
for(e = new enumerator(objwmiservice) ; !e.atend() ; e.movenext())
{
    var getcomputer = e.item();
    return getcomputer.name;
}
}

//条件编译

<script language=javascript>
/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>5)
function window.confirm(str)
{
    execscript("n = msgbox('"+ str +"', 257)", "vbscript");
    return(n == 1);
}
@end @*/
</script>

//取得innertext

<script language="javascript">
<!--
 var xmldoc = new activexobject("msxml2.domdocument.4.0");
 var currnode;
 xmldoc.async = false;
 xmldoc.async = false;
 xmldoc.loadxml("<tablename>      你好你阿三    大法     司法等四              </tablename>");
 currnode = xmldoc.documentelement;
   
  var s = currnode.xml;
  var r = //<([^/>/s]*?)[^/>]*?/>([^/<]*?)/<///1/>/
  var b = s.replace(r,"$2");
  alert(b);
//-->
</script>
//mergeattributes 复制所有读/写标签属性到指定元素。
<script>
function fnmerge(){
osource.children[1].mergeattributes(osource.children[0]);
}
</script>
<span id=osource>
<div
id="odiv"
attribute1="true"
attribute2="true"
onclick="alert('click');"
onmouseover="this.style.color='#0000ff';"
onmouseout="this.style.color='#000000';"
>
this is a sample <b>div</b> element.
</div>
<div id="odiv2">
this is another sample <b>div</b> element.
</div>
</span>
<input
type="button"
value="merge attributes"
onclick="fnmerge()"
>

检查链接是否有效

<a href=http://www.CuoXin.com onclick="mm(this, 'http://www.CuoXin.com/')">test</a>
<script language="javascript">
function geturl(url)
{
var xmlhttp = new activexobject("microsoft.xmlhttp");
xmlhttp.open("get",url,false);
xmlhttp.send();
if (xmlhttp.readystate==4) return xmlhttp.status==200;
return false;
}
function mm(e, url)
{
if(!geturl(e.href)) e.href = url;
}
</script>

判断是否输入值再激活按钮

<script>
function check(){
s.disabled = (t1.value == '' || t2.value == '' || t3.value == '')
}
</script>
<input name="t1" onpropertychange="check();">
<input name="t2" onpropertychange="check();">
<input name="t3" onpropertychange="check();">
<input type="submit" name="s" disabled>

屏蔽鼠标右键、ctrl+n、shift+f10、alt+f4、f11、f5刷新、退格键

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=gb2312">
  <noscript><meta http-equiv="refresh" content="0;url=about:noscript"></noscript>
  <title>屏蔽鼠标右键、ctrl+n、shift+f10、alt+f4、f11、f5刷新、退格键</title>
</head>
<body>
<script language="javascript"><!--
  //屏蔽鼠标右键、ctrl+n、shift+f10、f11、f5刷新、退格键
  //author: meizz(梅花雨) 2002-6-18
function document.oncontextmenu(){event.returnvalue=false;}//屏蔽鼠标右键
function window.onhelp(){return false} //屏蔽f1帮助
function document.onkeydown()
{
  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.keycode==116)||                 //屏蔽 f5 刷新键
      (event.ctrlkey && event.keycode==82)){ //ctrl + r
     event.keycode=0;
     event.returnvalue=false;
     }
  if (event.keycode==122){event.keycode=0;event.returnvalue=false;}  //屏蔽f11
  if (event.ctrlkey && event.keycode==78) event.returnvalue=false;   //屏蔽 ctrl+n
  if (event.shiftkey && event.keycode==121)event.returnvalue=false;  //屏蔽 shift+f10
  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;
  }
}
</script>
屏蔽鼠标右键、ctrl+n、shift+f10、alt+f4、f11、f5刷新、退格键
</body>
</html>

自定义热键(请按a)

自定义热键(请按a)
<script language="javascript">
<!--
var hotkey=97
var destination="http://www.CuoXin.com"
if (document.layers)
document.captureevents(event.keypress)
function backhome(e){
if (document.layers){
if (e.which==hotkey)
window.location=destination
}
else if (document.all){
if (event.keycode==hotkey)
window.location=destination
}
}
document.onkeypress=backhome
//-->
</script>

下面的是用javascript传递参数。如果本文件为test.htm,如果访问 test.htm?12 则javascript会得到?后的值并用document.all替换iframe的src值。

<iframe height="750" width="760" scrolling="no" src="view.jsp" id="u" frameborder="0"></iframe>
<script language="javascript">
var url=window.location.href;
var s=url.indexof("?");
if(s!=-1)
{
    var src=url.substring(s+1);
    document.all.u.src="view.jsp?id="+src;
   
}
</script>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表