---
title: "JavaScript实用小技巧"
author: "传说中的旅人"
date: "2011-04-18T10:06:36Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2011-04-23T12:55:46Z"
id: 1006047
url: "https://lengend.iteye.com/blog/1006047"
---

1\. oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键,可用于Table

```
<table border oncontextmenu=return(false)><td>no</table>
```

2\. 取消选取、防止复制

```
<body onselectstart="return false">
```

3\. 不准粘贴:onpaste="return false"  
4\. 防止复制:oncopy="return false;" oncut="return false;"  
5\. IE地址栏前换成自己的图标，先做一个16\*16的icon（图标文件），保存为favicon.ico。把这个图标文件上传到相应目录下。

```
<link rel="Shortcut Icon" href="favicon.ico">
```

6\. 可以在收藏夹中显示出你的图标

```
<link rel="Bookmark" href="favicon.ico">
```

7\. 关闭输入法

```
<input style="ime-mode:disabled"> 
```

8\. 永远都会带着框架

```
<script language="JavaScript"><!--
if (window == top)top.location.href = "frames.htm"; //frames.htm为框架网页
// --></script>
```

9\. 防止被人frame

```
<SCRIPT LANGUAGE=JAVASCRIPT><!-- 
if (top.location != self.location)top.location=self.location;
// --></SCRIPT>
```

10\. 网页将不能被另存为

```
<noscript><iframe src=*.html></iframe></noscript> 
```

11.查看网页源代码

```
<input type=button value=查看网页源代码 
onclick="window.location = "view-source:"+ "http://www.pconline.com.cn"">
```

12\. 光标是停在文本框文字的最后

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

13.最小化、最大化、关闭窗口

```
<object id=hh1 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"> 
<param name="Command" value="Minimize"></object>
<object id=hh2 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"> 
<param name="Command" value="Maximize"></object>
<OBJECT id=hh3 classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11">
<PARAM NAME="Command" VALUE="Close"></OBJECT>
<input type=button value=最小化 onclick=hh1.Click()>
<input type=button value=最大化 onclick=hh2.Click()>
<input type=button value=关闭 onclick=hh3.Click()>
```

本例适用于IE  
14.网页不会被缓存

```
<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
<META HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">
或者<META HTTP-EQUIV="expires" CONTENT="0">
```

15.&lt;div&gt;&lt;span&gt;&&lt;layer&gt;的区别？  
&lt;div&gt;(division)用来定义大段的页面元素，会产生转行  
&lt;span&gt;用来定义同一行内的元素，跟&lt;div&gt;的唯一区别是不产生转行  
&lt;layer&gt;是ns的标记，ie不支持，相当于&lt;div&gt;  
16.怎样去掉图片链接点击后，图片周围的虚线？

```
<a href="#" onFocus="this.blur()"><img src="logo.jpg" border=0></a>
```

17.在打开的子窗口刷新父窗口  
window.opener.location.reload()  
18.在页面中如何加入不是满铺的背景图片,拉动页面时背景图不动

```
<STYLE> 
body 
{background-image:url(logo.gif); background-repeat:no-repeat; 
background-position:center;background-attachment: fixed} 
</STYLE> 
```

19.TEXTAREA自适应文字行数

```
<textarea rows=1 name=s1 cols=27 onpropertychange="this.style.posHeight=this.scrollHeight">
</textarea>
```

20.选择了哪一个Radio

```
<HTML><script language="javascript">
function checkme(){
	for(var i=0 ;i < radios.length ; i++){
		 if(radios[i].checked){
			window.alert(radios[i].value);
		}
	}
}
</script><BODY>
<INPUT name="radios" type="radio" value="style" checked>Style
<INPUT name="radios" type="radio" value="barcode">Barcode
<INPUT type="button" value="check" onclick="checkme()">
</BODY></HTML>
```

21.脚本永不出错

```
<SCRIPT LANGUAGE="JavaScript"> 
<!-- Hide 
function killErrors() { 
return true; 
} 
window.onerror = killErrors; 
// --> 
</SCRIPT>
```

22.ENTER键可以让光标移到下一个输入框

```
<input onkeydown="if(event.keyCode==13)event.keyCode=9">
```

23.网页是否被检索  
&lt;meta name="ROBOTS" content="属性值"&gt;  
　　其中属性值有以下一些:  
　　属性值为"all": 文件将被检索，且页上链接可被查询；  
　　属性值为"none": 文件不被检索，而且不查询页上的链接；  
　　属性值为"index": 文件将被检索；  
　　属性值为"follow": 查询页上的链接；  
　　属性值为"noindex": 文件不检索，但可被查询链接；  
　　属性值为"nofollow": 文件不被检索，但可查询页上的链接。  
24.colgroup 标签 -- 表示对HTML表格进行结构化的分区,在此分区中可以通过使用col定义每列表格的样式 。

```
<style type="text/css">
.yellow{
     color: #CCCC33;
     font-size:36px;
}
.blue{
     color: #3399CC;
     font-size:12px;
}
</style>
<table border="1">
	<colgroup>
		<col />
		<col class="yellow" />
		<col />
		<col span="2" class="blue" />
	</colgroup> 
	<tr> 
		<th>www.dreamdu.com</th>
		<th>.com域名的数量</th>
		<th>.cn域名的数量</th>
		<th>.net域名的数量</th>
		<th>.com.cn域名的数量</th>
	</tr>
	<tr>
		<td>2003年</td>
		<td>1000</td>
		<td>2000</td>
		<td>3000</td>
		<td>4000</td>
	</tr>
</table>
```

25.格式化数字

```
/**  
 * 格式化数字显示方式   
 * @param num  
 * @param pattern  '#,##0.00' '#,##0.##' '000000'
 */  
function formatNumber(num,pattern){   
  var strarr = num?num.toString().split('.'):['0'];   
  var fmtarr = pattern?pattern.split('.'):[''];   
  var retstr='';   
  
  // 整数部分   
  var str = strarr[0];   
  var fmt = fmtarr[0];   
  var i = str.length-1;     
  var comma = false;   
  for(var f=fmt.length-1;f>=0;f--){   
    switch(fmt.substr(f,1)){   
      case '#':   
        if(i>=0 ) retstr = str.substr(i--,1) + retstr;   
        break;   
      case '0':   
        if(i>=0) retstr = str.substr(i--,1) + retstr;   
        else retstr = '0' + retstr;   
        break;   
      case ',':   
        comma = true;   
        retstr=','+retstr;   
        break;   
    }   
  }   
  if(i>=0){   
    if(comma){   
      var l = str.length;   
      for(;i>=0;i--){   
        retstr = str.substr(i,1) + retstr;   
        if(i>0 && ((l-i)%3)==0) retstr = ',' + retstr;    
      }   
    }   
    else retstr = str.substr(0,i+1) + retstr;   
  }   
  
  retstr = retstr+'.';   
  // 处理小数部分   
  str=strarr.length>1?strarr[1]:'';   
  fmt=fmtarr.length>1?fmtarr[1]:'';   
  i=0;   
  for(var f=0;f<fmt.length;f++){   
    switch(fmt.substr(f,1)){   
      case '#':   
        if(i<str.length) retstr+=str.substr(i++,1);   
        break;   
      case '0':   
        if(i<str.length) retstr+= str.substr(i++,1);   
        else retstr+='0';   
        break;   
    }   
  }   
  return retstr.replace(/^,+/,'').replace(/\.$/,'');   
}   
```

26.数字验证

```
/^(-|\+)?\d+$/.test(str) //整数
/^\d+$/.test(str) //大于0的整数
/^-\d+$/.test(str) //负整数的验证
```

27.时间验证

```
function isCorrectTime(str){ //like:13:04:06
    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; 
} 
function isCorrectDate(str){ //2003-12-05
    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]); 
} 
function isCorrectDateTime(str){ //2003-12-05 13:04:06
    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]); 
}
 
```

28.去掉前后空白

```
this.value.replace(/^\s+|\s+$/g,'')=='')
```

29.操作select

```
if(objselect.selectedIndex > -1) {alert('selected');}//是否有选中
objselect.options[objselect.selectedIndex] = null;//删除被选中的项
objselect.options[objselect.length] = new Option("text","value");//增加项
objselect.options[objselect.selectedIndex].text;//得到所选择项的文本
objselect.options[objselect.selectedIndex].value;//得到所选择项的值
document.getElementByid("el").tabIndex = 1;//焦点顺序
```

30.添加到收藏夹:

```
window.external.AddFavorite('http://www.java.com');
```

31.模态对话框  
window.showModelessDialog()方法用来创建一个显示HTML内容的非模态对话框。  
window.showModalDialog()方法用来创建一个显示HTML内容的模态对话框，由于  
是对话框，因此它并没有一般用window.open()打开的窗口的所有属性。  
只是,FireFox浏览器中不支持showmodaldialog()，用window.open。在Firefox下,window.open的参数中,sFeature多了一些功能设定,要让FireFox下开启的窗口跟IE的showModalDialog一样的话,只要在sFeatures中加个modal=yes就可以了,也许可能是出于安全考虑modal=yes 打开的并不是模式窗口。

```
<input type="button" value="打开对话框" onclick="showDialog('#')"/>   
  <SCRIPT   LANGUAGE="JavaScript">   
  <!--   
  function  showDialog(url){   
   if(document.all){//IE
     feature="dialogWidth:300px;dialogHeight:200px;status:no;help:no";   
   window.showModalDialog(url,null,feature);   
   }else{   
     //modelessDialog可以将modal换成dialog=yes   
   feature ="width=300,height=200,menubar=no,toolbar=no,location=no,";   
   feature+="scrollbars=no,status=no,modal=yes";     
   window.open(url,null,feature);   
   }   
  }   
  //-->   
</SCRIPT> 
```

传参数与返回值：

```
var gArgs = window.dialogArguments;
```

```
var dlg = window.showModalDialog("test.htm",arg); 
```

```
window.returnValue = {flag:true;}; 
window.close();
```

32.屏蔽打印按钮

```
<style type="text/css">
<!--
@media print { 
	.disp{
		display: none;		
	}
}
-->
</style>
```

33.动态改变CSS

```
function changeLinkCss(url){
	var link_css=document.getElementsByTagName('link');
	for(var i=0;i<link_css.length;i++){
		if(link_css[i].rel.toLowerCase() == 'stylesheet'){
			link_css[i].href = url;
		}
	}
}
```

34.置下一元素焦点

```
function setNextFocus(){
    var srcObj = event.srcElement;
	var len = document.all.length;
	var idx = -1;
	for(var i=0; i<len; i++){
	    var curObj = document.all[i];
		if(curObj == srcObj){
			idx = i;
			break;
		}
	}
	if(idx != -1 && idx < len-1){
		for(var j=idx+1 ;j<len;j++){
			if(checkTags(document.all[j])){
				document.all[j].focus();
				return;
			}
		}
	}
}

function checkTags(obj){
	if(obj.readOnly == true || obj.disabled == true) {return false;}
    var tag_name = obj.tagName;
   	var el_tags = ['select','input','textarea'];
	for(var i=0; i<el_tags.length; i++){
		if(el_tags[i] == tag_name.toLowerCase()){
			return true;
		}
	}
	return false;
}
```

35.获得当前目录路径

```
function getCurrentDirectory(){
var locHref = location.href;
var locArray = locHref.split("/");
/**这里测试locArray效果**
    for(x in locArray){
      document.write("locArray[");
      document.write(x+"]: ");
      document.write(locArray[x]+"<br />");
    }
    **/
    delete locArray[locArray.length-1];
    var dirTxt = locArray.join("/");
    return dirTxt;
}
document.write(getCurrentDirectory());
```

36.清空file域  
innerHTML 设置或获取位于对象起始和结束标签内的 HTML  
outerHTML 设置或获取对象及其内容的 HTML 形式  
innerText 设置或获取位于对象起始和结束标签内的文本  
outerText 设置(包括标签)或获取(不包括标签)对象的文本

```
function Clean(){  
   var obj=document.getElementById("UpFile");
   obj.outerHTML=obj.outerHTML;
}
```

37.js之arguments  
使用JavaScript函数内置的arguments可以遍历所有传入的参数。arguments有个callee属性，可以调用arguments自身所在的函数。也就是说，可以通过这个属性递归调用函数自身。

```
function sum() {   
    var total = 0;   
    for(var i = 0; i < arguments.length; i++) {   
        total += arguments[i];   
    }   
    alert(total);   
}   
sum(1, 2);   
sum(1, 2, 3);  
```

```
function sum(n) {   
    if(n <= 1) {   
        return 1;   
    }   
    return n + arguments.callee(n - 1); // 递归调用自身   
}   
alert(sum(100));  
```

38.document.execCommand()

```
<input type=button value=剪切 onclick=document.execCommand('Cut')>
<input type=button value=拷贝 onclick=document.execCommand('Copy')>
<input type=button value=粘贴 onclick=document.execCommand('Paste')>
<input type=button value=撤消 onclick=document.execCommand('Undo')>
<input type=button value=重做 onclick=document.execCommand('Redo') id=button2 name=button2>
<input>
<input type=button value=删除 onclick=document.execCommand('Delete')>
<input type=button value=黑体 onclick=document.execCommand('Bold')>
<input type=button value=斜体 onclick=document.execCommand('Italic')>
<input type=button value=下划线 onclick=document.execCommand('Underline')>
<input type=button value=停止 onclick=document.execCommand('stop')>
<input type=button value=保存 onclick=document.execCommand('SaveAs')>
<input type=button value=另存为 onclick=document.execCommand('Saveas',false,'c:\\test.htm')>
<input type=button value=字体 onclick=document.execCommand('FontName',false,fn)>
<input type=button value=字体大小 onclick=document.execCommand('FontSize',false,fs)>
<input type=button value=刷新 onclick=document.execCommand('refresh',false,0)>-
```

isNaN是测试是否为数值型 ，限制输入只能为数值如：1981.121，允许最多有一个小数点  
&lt;input type="text" name="text" onkeyup="if(isNaN(value))execCommand('undo')" /&gt;  
IE6下默认不缓存背景图片，CSS里每次更改图片的位置时都会重新发起请求，用这个方法告诉IE6缓存背景图片。

```
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}
```

39.取消事件冒泡  
在 IE 的事件机制中，触发事件会从子元素向父元素逐级上传，就是说，如果子元素触发了单击事件，那么也会触发父元素的单击事件；

```
event.cancelBubble=true;
```

可以停止事件继续上传补充一点，Ie的事件传递是从下到上的：  
事件来源对象-&gt;上级对象-&gt;上上级对象-&gt;.....-&gt;body-&gt;document-&gt;window  
40.禁止选择文字

```
<div unselectable="on" onselectstart="return false;" style="-moz-user-select:none;" >禁止选择,unselectable为IE准备 ， onselectstart为Chrome、Safari准备    -moz-user-select是FF的 </div>
```

41.js释放内存  
CollectGarbage,是IE的一个特有属性,用于释放内存的，使用方法嘛应该是,将该变量或引用对象,设置为null或delete，然后在进行释放动作，在做CollectGarbage前,要必需清楚的两个必备条件:  
(1)一个对象在其生存的上下文环境之外，即会失效。  
(2)一个全局的对象在没有被执用(引用)的情况下，即会失效。

```
System.gc   =   function   ()   
  {   
  　　if   (System.isIeBrowser())   
  　　{   
  　　　　CollectGarbage();   
  　　　　setTimeout("CollectGarbage();",   1);   
  　　}   
  }   
```

42.QVOD播放器代码

```
<object classid="clsid:F3D0D36F-23F8-4682-A195-74C92B03D4AF" width="500" height="400" id="QvodPlayer" name="QvodPlayer" onError=if(window.confirm('请您先安装QvodPlayer软件,然后刷新本页才可以正常播放.')){window.open('http://www.qvod.com/download.htm')}else{self.location='http://www.qvod.com/'}>
   <PARAM NAME='URL'
          VALUE='此处请替换成QVOD播放链接地址'>
   <PARAM NAME='Autoplay' VALUE='1'>  
</object>
```

43.图片旋转

```
function imageTurn(id,filter){//水平："fliph"与垂直："flipV"
	var img = document.getElementById(id);
	img.style.filter = img.style.filter ==filter ? "" : filter;
}
```

44.设置一组css属性

```
function setStyle(obj,css){   
  for(var atr in css)   
    obj.style[atr] = css[atr];   
}   
var head= document.getElementById("head");   
setStyle(head,{width:"200px",height:"70px",display:"block"});  
```

```
var head= document.getElementById("head");   
head.style.cssText="width:200px;height:70px;display:bolck";  
```

45.滤镜RevealTrans (duration=转换的秒数，transition=转换的类型）  
transition的取值为0-23。代表24种过渡效果。可以用在整个页面上，也可以用在页面的某一个物件上。

```
<META http-equiv='Page-Exit’ CONTENT='RevealTrans(Duration=0.5,Transition=23)'>
```

```
<img id="img1" src="img1.jpg" width="300" height="226" style="filter:revealTrans(Transition=1,Duration=1.5);" />
```

**46.不用eval,解析JSON**

```
function jsonDecode(data){ 
    return (new Function("return " + data))(); 
} 
```

其他要想实现类似的eval的功能，一般都是在DOM中创建一个script节点，然后script.text = data;  
**47、不提示关闭窗口**

```
function closeWindow(){
  window.opener=null;
  window.open('','_self');
  window.close();
}
```

**48、数组元素去重**

```
function removeDuplicate(array){
	for(var i=0;i<array.length;i++){   
		for(var j=i+1;j<array.length;j++){   
		   if(array[j]===array[i]) {   
			   array.splice(j,1);   
			   j--;   
			 }   
		}   
	}
	return array;
}
```