1、事件冒泡
当一个元素上的事件被触发的时候,比如说鼠标点击了一个按钮,同样的事件将会在那个元素的所有祖先元素中被触发。这 一过程被称为事件冒泡;这个事件从原始元素开始一直冒泡到DOM树的最上层
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>bubble</title>
<style>
button{
background: red;
color:white;
}
#third{
width: 50px;
height: 50px;
border:thin solid red;
}
#second{
width: 100px;
height: 100px;
border:thin solid red;
}
#first{
width:200px;
height: 200px;
border:thin solid red;
}
</style>
</head>
<body>
<div id="first">
<div id="second" >
<div id="third" >
<button id="button">事件冒泡</button>
</div>
</div>
</div>
<script>
document.getElementById("button").addEventListener("click",function(){
alert("button");
},false);
document.getElementById("third").addEventListener("click",function(){
alert("third");
},false);
document.getElementById("second").addEventListener("click",function(){
alert("second");
},false);
document.getElementById("first").addEventListener("click",function(){
alert("first");
},false);
</script>
</body>
</html>
点击button元素,但是,button外的third、second、first上的事件由内向外以此被触发,触发的顺序是由DOM树的下层到DOM树的最上面,故称为冒泡
阻止冒泡:
事件的对象有一个stopPropagation()方法可以阻止事件冒泡
document.getElementById("button").addEventListener("click",function(event){
alert("button");
event.stopPropagation();
},false);
点击button后,只会弹出一个弹窗,显示button
2、事件捕获
事件捕获是指不太具体的节点应该更早的接收到事件,而最具体的节点应该最后接收到事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>bubble</title>
<style>
button{
background: red;
color:white;
}
#third{
width: 50px;
height: 50px;
border:thin solid red;
}
#second{
width: 100px;
height: 100px;
border:thin solid red;
}
#first{
width:200px;
height: 200px;
border:thin solid red;
}
</style>
</head>
<body>
<div id="first">
<div id="second" >
<div id="third" >
<button id="button">事件冒泡</button>
</div>
</div>
</div>
<script>
document.getElementById("button").addEventListener("click",function(){
alert("button");
},true);
document.getElementById("third").addEventListener("click",function(){
alert("third");
},true);
document.getElementById("second").addEventListener("click",function(){
alert("second");
},true);
document.getElementById("first").addEventListener("click",function(){
alert("first");
},true);
</script>
</body>
</html>
最外层的事件先被触发,最后才是点击的button事件被触发
阻止事件捕获
stopPropagation()方法既可以阻止事件冒泡,也可以阻止事件捕获,也可以阻止处于目标阶段。
可以使用DOM3级新增事件stopImmediatePropagation()方法来阻止事件捕获,另外此方法还可以阻止事件冒泡
document.getElementById("second").addEventListener("click",function(){
alert("second");
event.stopImmediatePropagation();
},true);