1、什么是事件冒泡
IE的事件流叫做事件冒泡(event bubbling),即事件开始时由最具体的元素接收,然后逐级向上传播到较为不具体的节点。
2、如何利用事件冒泡
- 事件冒泡允许多个操作被集中处理(把事件处理器添加到一个父级元素上,避免把事件处理器添加到多个子级元素上),它还可以让你在对象层的不同级别捕获事件。
<div onclick="eventHandle(event)" id="outSide"
style="width:100px;
height:100px;
background:#000;
padding:50px">
<div id="inSide" style="width:100px; height:100px; background:#CCC"></div>
</div>
function eventHandle (e) {
var e=e||window.event;
var obj=e.target||e.srcElement;
console.log(obj.id+' was click')
}
0.jpg
- 让不同的对象同时捕获同一事件,并调用自己的专属处理程序做自己的事情
<div onclick="outSideWork()"
id="outSide"
style="width:100px; height:100px; background:#000; padding:50px">
<div onclick="inSideWork()"
id="inSide"
style="width:100px; height:100px; background:#CCC"></div>
</div>
function outSideWork(){ // 点击外层div,内层不会被触发
alert('My name is outSide,I was working...');
}
function inSideWork(){ // 点击里面的div,这个事件完了再直接上一层
alert('My name is inSide,I was working...');
}
3、如何阻止冒泡
e.stopPropagation()
window.event.cancelBubble = true
<div onclick="showMsg(this,event)"
id="outSide"
style="width:100px; height:100px; background:#000; padding:50px">
<div onclick="showMsg(this,event)"
id="inSide"
style="width:100px; height:100px; background:#CCC"></div>
</div>
function stopBubble(e){
if (e && e.stopPropagation)
e.stopPropagation()
else
window.event.cancelBubble=true
}
function showMsg(obj,e){
alert(obj.id);
stopBubble(e)
}
网友评论