事件对象的重要属性与方法
如何调用事件对象:
非ie浏览器:事件对象是通过传参来调用的
ie浏览器(ie9以下浏览器版本):事件对象是window对象的一个属性,直接调用window.event
W3C(ie9也支持)事件对象包括的几个重要属性和方法:
bubbles(默认为true,表示事件是否冒泡),
cancelable(默认为true,表示是否可以取消事件的默认行为),
type(事件的类型),
target(事件的目标),
currentTraget(正在处理事件的那个元素)
stopPropagation():取消事件的进一步捕获或冒泡,
preventDefault():取消事件的默认行为
【ie9以下版本浏览器不支持target,currentTarget】
IE事件对象包括的几个重要属性:
cancelBubble(默认为false,设置true,可以取消事件冒泡),
returnValue(默认为true,设置false,可以取消事件的默认行为),
type(事件的类型),
srcElement(事件的目标)
阻止事件冒泡和浏览器默认行为的两个方法
阻止事件冒泡:
function stopBubble(e){ if (e && e.stopBubble){ e.stopPropagation(); }else{ window.event.cancelBubble = true; } }
阻止浏览器的默认行为:
function stopDefault(e){ if (e && e.preventDefault){ e.preventDefault(); }else{ window.event.returnValue = false; } }
DOM标准事件对象属性(target)与IE事件对象属性(srcElement)在不同情况下表示不同
html代码结构:
<div class="box-wrap" id="box-wrap"> <p class="box-child" id="box-child">内容 </p> </div>
css代码:
.box-wrap { width: 52px; height: 52px; margin: 0 auto; background: #09F; } .box-child { display: block; margin: 0 auto; width: 50px; height: 50px; line-height: 50px; border: 1px solid #F00; text-align: center; color: #FFF; }
如图:

var box = document.getElementById("box-wrap"); var p = document.getElementById("box-child");
情况一(已阻止事件冒泡):
p.onclick = function(e){ //阻止事件冒泡 stopBubble(e); if(!-[1,]){ //如果是ie浏览器 console.log(window.event.srcElement); //显示日志为:p元素 }else{ //非ie浏览器 console.log(e.target); //显示日志为:p元素 console.log(e.currentTarget); //显示日志为:p元素 } }
情况二(有事件冒泡):
box.onclick = function(e){ if(!-[1,]){ //如果是ie浏览器 console.log(window.event.srcElement); //显示日志为:p元素 }else{ //非ie浏览器 console.log(e.target); //显示日志为:p元素 console.log(e.currentTarget); //显示日志为:div元素 } }
【通过上面两种情况说明,IE中事件对象中的srcElement等同于DOM标准事件对象中的target属性】
情况三(把html中p元素换成a元素):
【IE中的srcElement等于a链接的url属性值,在ie9中,target,currentTarget等于a链接的url属性值】