一、获取目标
位于事件中心的对象称为目标(target).假设为<div/>元素分配onclick事件处理函数、触发click事件时、<div/>就被认为是目标。IE、目标包含在event对象的srcElement属性中:javascript
- var oTarget = oEvent.srcElement;
在DOM兼容的浏览器中、目标包含在target属性中:html
- var oTarget = oEvent.target;
示例:java
- <div id="divId" onclick="testFunction(event)">点击 </div>
- <script type="text/javascript" >
- var sUserAgent = navigator.userAgent;
- var isIE = sUserAgent.indexOf("compatible") > -1 && sUserAgent.indexOf("MSIE") > -1;
- var isMoz = sUserAgent.indexOf("Gecko") > -1;
- function testFunction(oEvent){
- if(isIE){
- alert("IE");
- var oEvent = window.event;
- //IE、目标包含在event对象的srcElement属性中:
- var oTarget = oEvent.srcElement;
- alert(oTarget.innerText);
- return;
- }
- if(isMoz){
- alert("火狐: "+oEvent);
- /**
- *
- * 直接innerText这样火狐不支持、它支持innerHTML
- * 因此要用innerText须要处理一下.
- *
- * 让火狐兼容innerText**/
- HTMLElement.prototype.__defineGetter__("innerText",
- function ()
- {
- var anyString = "";
- var childS = this.childNodes;
- for (var i = 0; i < childS.length; i++)
- {
- if (childS[i].nodeType == 1)
- anyString += childS[i].tagName == "BR"
- ? "\r\n" : childS[i].textContent;
- else if (childS[i].nodeType == 3)
- anyString += childS[i].nodeValue;
- }
- return anyString;
- });
- HTMLElement.prototype.__defineSetter__("innerText",
- function (sText)
- {
- this.textContent = sText;
- });
- /**end**/
- //在DOM兼容的浏览器中、目标包含在target属性中:
- var oTarget = oEvent.target;
- alert(oTarget.innerText);
- return;
- }
- }
- </script>
二、阻止某个事件的默认行为IE必须将returnValue属性设值为false:node
- oEvent.returnValue = false;
而在Mozilla中、只要调用preventDefault()方法:浏览器
- oEvent.preventDefault();
用户右击页面时、阻止他使用菜单。只要阻止contextmenu事件的默认行为就能够了:ide
- doucment.body.oncontextmenu = function (oEvent){
- if(isIE){
- oEvent = window.event;
- oEvent.returnValue = false;
- }else{
- oEvent.preventDefault();
- }
- };
三、中止事件复制(冒泡)
IE中、要阻止事件进一步冒泡、必须设置cancelBubble属性为true:函数
- oEvent.cancelBubble = true;
在Mozilla中、只需调用stopPropagation()方法:this
- oEvent.stopPropagation();
中止事件复制能够阻止事件流中的其它对象的事件处理函数执行、点击下面button按钮会弹出input、body、html这是由于事件先从input元素冒泡到body、而后到html :spa
- <html onclick="alert('html');">
- <head>
- <title>中止事件复制(冒泡)</title>
- </head>
- <body onclick="alert('body');">
- <input type="button" onclick="alert('input');" value="点击" />
- </body>
- </html>
下面就在按钮上中止复制(冒泡):prototype
- <html onclick="alert('html');">
- <head>
- <title>中止事件复制(冒泡)</title>
- <script type="text/javascript">
- var sUserAgent = navigator.userAgent;
- var isIE = sUserAgent.indexOf("compatible") > -1 && sUserAgent.indexOf("MSIE") > -1;
- function testClick(oEvent){
- alert("input");
- if(isIE){
- var oEvent = window.event;
- oEvent.cancelBubble = true;
- }else{
- oEvent.stopPropagation();
- }
- }
- </script>
- </head>
- <body onclick="alert('body');">
- <input type="button" onclick="testClick(event);" value="点击" />
- <br />
- </body>
- </html>