JavaScript实用小技巧
1. oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键,可用于Table
<table border oncontextmenu=return(false)><td>no</table>
<body onselectstart="return false">
<link rel="Shortcut Icon" href="favicon.ico">
<link rel="Bookmark" href="favicon.ico">
<input style="ime-mode:disabled">
<script language="JavaScript"><!--if (window == top)top.location.href = "frames.htm"; //frames.htm为框架网页// --></script>
<SCRIPT LANGUAGE=JAVASCRIPT><!-- if (top.location != self.location)top.location=self.location;// --></SCRIPT>
<noscript><iframe src=*.html></iframe></noscript>
<input type=button value=查看网页源代码 onclick="window.location = "view-source:"+ "http://www.pconline.com.cn"">
<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()"><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
<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">
<a href="#" onFocus="this.blur()"><img src="logo.jpg" border=0></a>
<STYLE> body {background-image:url(logo.gif); background-repeat:no-repeat; background-position:center;background-attachment: fixed} </STYLE> <textarea rows=1 name=s1 cols=27 onpropertychange="this.style.posHeight=this.scrollHeight"></textarea>
<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><SCRIPT LANGUAGE="JavaScript"> <!-- Hide function killErrors() { return true; } window.onerror = killErrors; // --> </SCRIPT><input onkeydown="if(event.keyCode==13)event.keyCode=9">
<style type="text/css">.yellow{ color: #CCCC33; font-size:36px;}.blue{ color: #3399CC; font-size:12px;}</style><table border="1"><colgroup><col /><col /><col /><col span="2" /></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>/** * 格式化数字显示方式 * @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(/\.$/,''); } /^(-|\+)?\d+$/.test(str) //整数/^\d+$/.test(str) //大于0的整数/^-\d+$/.test(str) //负整数的验证
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]); } this.value.replace(/^\s+|\s+$/g,'')=='')
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;//焦点顺序window.external.AddFavorite('http://www.java.com');<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();<style type="text/css"><!--@media print { .disp{display: none;}}--></style>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;}}}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;}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());function Clean(){ var obj=document.getElementById("UpFile"); obj.outerHTML=obj.outerHTML;}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)); <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)>-try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}event.cancelBubble=true;可以停止事件继续上传补充一点,Ie的事件传递是从下到上的:
<div unselectable="on" onselectstart="return false;" style="-moz-user-select:none;" >禁止选择,unselectable为IE准备 , onselectstart为Chrome、Safari准备 -moz-user-select是FF的 </div>
System.gc = function () { if (System.isIeBrowser()) { CollectGarbage(); setTimeout("CollectGarbage();", 1); } } <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>function imageTurn(id,filter){//水平:"fliph"与垂直:"flipV"var img = document.getElementById(id);img.style.filter = img.style.filter ==filter ? "" : filter;}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"; <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);" />
function jsonDecode(data){ return (new Function("return " + data))(); } function closeWindow(){ window.opener=null; window.open('','_self'); window.close();}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;}