javascript 应用小技巧方法汇总
事件源对象 event.srcElement.tagName
event.srcElement.type
捕获释放 event.srcElement.setCapture();
event.srcElement
javascript 在前端应用体验小技巧继续积累。
事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElement.setCapture(); event.srcElement.releaseCapture(); 事件按键 event.keyCode event.shiftKey event.altKey event.ctrlKey 事件返回值 event.returnValue 鼠标位置 event.x event.y 窗体活动元素 document.activeElement 绑定事件 document.captureEvents(Event.KEYDOWN); 访问窗体元素 document.all("txt").focus(); document.all("txt").select(); 窗体命令 document.execCommand 窗体COOKIE document.cookie 菜单事件 document.oncontextmenu 创建元素 document.createElement("SPAN"); 根据鼠标获得元素: document.elementFromPoint(event.x,event.y).tagName=="TD document.elementFromPoint(event.x,event.y).appendChild(ms) 窗体图片 document.images[索引] 窗体事件绑定 document.onmousedown=scrollwindow; 元素 document.窗体.elements[索引] 对象绑定事件 document.all.xxx.detachEvent('onclick',a); 插件数目 navigator.plugins 取变量类型 typeof($js_libpath) == "undefined" 下拉框 下拉框.options[索引] 下拉框.options.length 查找对象 document.getElementsByName("r1"); document.getElementById(id); 定时 timer=setInterval('scrollwindow()',delay); clearInterval(timer); UNCODE编码 escape() ,unescape 父对象 obj.parentElement(dhtml) obj.parentNode(dom) 交换表的行 TableID.moveRow(2,1) 替换CSS document.all.csss.href = "a.css"; 并排显示 display:inline 隐藏焦点 hidefocus=true 根据宽度换行 style="word-break:break-all" 自动刷新 <meta HTTP-EQUIV="refresh" CONTENT="8;URL=http://c98.yeah.net"> 简单邮件 <a href="mailto:aaa@bbb.com?subject=ccc&body=xxxyyy"> 快速转到位置 obj.scrollIntoView(true) 锚 <a name="first"> <a href="#first">anchors</a> 网页传递参数 location.search(); 可编辑 obj.contenteditable=true 执行菜单命令 obj.execCommand 双字节字符 /[^\x00-\xff]/ 汉字 /[\u4e00-\u9fa5]/ 让英文字符串超出表格宽度自动换行word-wrap: break-word; word-break: break-all; 透明背景 <IFRAME src="1.htm" width=300 height=180 allowtransparency></iframe> 获得style内容 obj.style.cssText HTML标签 document.documentElement.innerHTML 第一个style标签 document.styleSheets[0] style标签里的第一个样式 document.styleSheets[0].rules[0] 防止点击空链接时,页面往往重置到页首端。 <a href="javascript:function()">word</a> 上一网页源 asp: request.servervariables("HTTP_REFERER") javascript: document.referrer 释放内存 CollectGarbage(); 禁止右键document.oncontextmenu = function() { return false;} 禁止保存 <noscript><iframe src="*.htm"></iframe></noscript> 禁止选取<body oncontextmenu="return false" ondragstart="return false" onselectstart ="return false" onselect="document.selection.empty()" oncopy="document.selection.empty()" onbeforecopy="return false"onmouseup="document.selection.empty()> 禁止粘贴 <input type=text onpaste="return false"> 地址栏图标 <link rel="Shortcut Icon" href="favicon.ico"> favicon.ico 名字最好不变16*16的16色,放虚拟目录根目录下 收藏栏图标 <link rel="Bookmark" href="favicon.ico"> 查看源码 <input type=button value=查看网页源代码 onclick="window.location = 'view-source:'+ 'http://www.csdn.net/'"> 关闭输入法 <input style="ime-mode:disabled"> 自动全选<input type=text name=text1 value="123" onfocus="this.select()"> ENTER键可以让光标移到下一个输入框 <input onkeydown="if(event.keyCode==13)event.keyCode=9"> 文本框的默认值 <input type=text value="123" onfocus="alert(this.defaultValue)"> title换行 obj.title = "123 sdfs " 获得时间所代表的微秒 var n1 = new Date("2004-10-10".replace(/-/g, "\/")).getTime() 窗口是否关闭 win.closed checkbox扁平 <input type=checkbox style="position: absolute; clip:rect(5px 15px 15px 5px)"><br> 获取选中内容 document.selection.createRange().duplicate().text 自动完成功能 <input type=text autocomplete=on>打开该功能 <input type=text autocomplete=off>关闭该功能 窗口最大化 <body onload="window.resizeTo(window.screen.width - 4,window.screen.height-50);window.moveTo(-4,-4)"> 无关闭按钮IE window.open("aa.htm", "meizz", "fullscreen=7"); 统一编码/解码 alert(decodeURIComponent(encodeURIComponent("http://你好.com?as= hehe"))) encodeURIComponent对":"、"/"、";" 和 "?"也编码 表格行指示 <tr onmouseover="this.bgColor='#f0f0f0'" onmouseout="this.bgColor='#ffffff'">
//各种尺寸
s += "\r\n网页可见区域宽:"+ document.body.clientWidth; s += "\r\n网页可见区域高:"+ document.body.clientHeight; s += "\r\n网页可见区域高:"+ document.body.offsetWeight +" (包括边线的宽)"; s += "\r\n网页可见区域高:"+ document.body.offsetHeight +" (包括边线的宽)"; s += "\r\n网页正文全文宽:"+ document.body.scrollWidth; s += "\r\n网页正文全文高:"+ document.body.scrollHeight; s += "\r\n网页被卷去的高:"+ document.body.scrollTop; s += "\r\n网页被卷去的左:"+ document.body.scrollLeft; s += "\r\n网页正文部分上:"+ window.screenTop; s += "\r\n网页正文部分左:"+ window.screenLeft; s += "\r\n屏幕分辨率的高:"+ window.screen.height; s += "\r\n屏幕分辨率的宽:"+ window.screen.width; s += "\r\n屏幕可用工作区高度:"+ window.screen.availHeight; s += "\r\n屏幕可用工作区宽度:"+ window.screen.availWidth;
//过滤数字
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,''))"
//消除图像工具栏
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"))
//检查网页是否存在
xmlhttp.Send(); var result = xmlhttp.status; } catch(e) {return(false); } if(result==200) { return true;
} xmlhttp = null; return false;
}
//连接数据库
+"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>
//使用数据岛
<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>
//获得参数
<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
<option value="1">11111111<option>
<option value="2">222222</option>
<option value="3">333333</option>
</select> </span>
//设置光标位置
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; }
//页内查找
{ 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
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>
//插入文字
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')
//判断键值
<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+"×"+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+"×"+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()" >
以上所述就是本文的全部内容了,希望大家能够喜欢。