冒泡和捕獲的區別是冒泡事件是先觸發子元素事件,再觸發父元素事件,這個是冒泡。捕獲是先觸發父元素事件,再觸發子元素事件。簡單的來說,冒泡的順序是由內到外,捕獲的順序是由外到內
舉例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#son{
width: 200px;
height: 200px;
background-color: yellow;
}
#father{
width: 400px;
height: 400px;
background-color: red;
}
</style>
</head>
<body>
<div id="father">
<div id="son">
</div>
</div>
</body>
<script>
var father=document.getElementById("father");
var son=document.getElementById("son");
function outSide(){
console.log("我是父元素事件")
}
function inSide(){
console.log("我是子元素事件")
}
//測試冒泡 執行結果為先出現我是子元素,再出現我是父元素,證明元素執行的順序是由內到外
// son.addEventListener("click",inSide,false);
// father.addEventListener("click",outSide,false);
// 測試捕獲 執行結果是先出現我是父元素,再出現我是子元素,證明元素的執行順序是由外到內
son.addEventListener("click",inSide,true);
father.addEventListener("click",outSide,true);
</script>
</html>
阻止事件冒泡:
function load(){
console.log('body')
}
function cli(e){
console.log('div');
if ( e && e.stopPropagation ){
e.stopPropagation();
}
else{
window.event.cancelBubble = true;
return false;
}
}
需要注意,在一些特殊事件中,本身就屏蔽了事件的冒泡
mouseout和mouseover 支持事件冒泡
mouseenter和mouseleave 則會自動阻止事件冒泡
target和currenttarget的區別 target指的是事件的真正觸發者,currenttarget指的是事件的監聽者,當不存在冒泡或者捕獲的情況下,通常兩者指向的對象為同一個,但是如果存在冒泡或者捕獲,
就會指向各自所產生的對象
代碼舉例
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#out{
width: 400px;
height:400px;
background-color:yellow;
}
#in{
width: 200px;
height:200px;
background-color:red;
}
</style>
</head>
<body>
<div id="out">
<div id="in"></div>
</div>
</body>
<script>
var out=document.getElementById("out");
var inner=document.getElementById("in");
out.addEventListener("click",function(e){
console.log("我在外面");
console.log(e.target);
console.log(e.currentTarget);
},false);
inner.addEventListener("click",function(e){
console.log("冒泡了");
console.log(e.target);
console.log(e.currentTarget);
},false);
此時點擊out元素時,因為不觸發冒泡事件,所以e.target和e.currentTarget的輸出結果均為id=out的div,也就是大盒子觸發了監聽事件。
但是當點擊in元素的時候,測觸發冒泡,此時in元素的 e.target和e.currentTarget相同(因為原本點擊的就是In元素),但因為冒泡,其父元素out也會產生監聽事件
而此時 out元素的 e.target 為 in 元素,因為確實點擊的是 in元素(target指向真正的觸發元素),而e.currentTarget輸出則為out元素(產生監聽的事件的元素)。
稍微自己總結了下,也不知道對不對:在通常情況下 e.target和e.currentTarget相同而在產生了冒泡或者捕獲的元素中,非點擊元素的 e.target和e.currentTarget不同.