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);
