捕獲和冒泡是相對於其他級元素的,例如:父級元素或子級元素
- 捕獲按父級到子級的順序觸發事件;
- 目標即為被點擊的元素;
- 冒泡按子級到父級的順序觸發事件;
阻止捕獲:e.stopImmediatePropagation();
//既可以阻止捕獲又可以阻止冒泡
阻止冒泡:e.stopPropagation();
舉例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="grandfather" style="background-color:#ff00006e;width:300px;height:200px;">
<p>祖父</p>
<div id="father" style="background-color:#ffff006e;width:200px;height:150px;">
<p>父親</p>
<div id="son" style="background-color:#0080006e;width:100px;height:100px;">
<p>兒子</p>
</div>
</div>
</div>
<script>
var flag = flase;//true捕获阶段;false冒泡阶段,默認為false。
document.getElementById("grandfather").addEventListener("click",function(e) {
alert("我是祖父");
}, flag);
document.getElementById("father").addEventListener("click",function(e) {
alert("我是父親");
}, flag);
document.getElementById("son").addEventListener("click",function(e) {
alert("我是兒子");
}, flag);
</script>
</body>
</html>
flag
為false
時,
- 點擊兒子:“我是兒子”>>“我是父親”>>“我是祖父”;
- 點擊父親:“我是父親”>>“我是祖父”;
- 點擊祖父:“我是祖父”;
flag
為true
時,
- 點擊兒子:“我是祖父”>>“我是父親”>>“我是兒子”;
- 點擊父親:“我是祖父”>>“我是父親”;
- 點擊祖父:“我是祖父”;