事件冒泡的案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.father {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: pink;
text-align: center;
}
.son {
width: 200px;
height: 200px;
margin: 50px;
background-color: purple;
line-height: 200px;
color: #fff;
}
</style>
</head>
<body>
<div class="father">
<div class="son">son盒子</div>
</div>
<script>
// 冒泡阶段 如果addEventListener 第三个参数是 false 或者 省略 那么则处于冒泡阶段
//son -> father ->body -> html -> document
var son = document.querySelector('.son');
son.addEventListener('click', function() {
alert('son');
}, false);
var father = document.querySelector('.father');
father.addEventListener('click', function() {
alert('father');
}, false);
document.addEventListener('click', function() {
alert('document');
});
</script>
</body>
</html>
可以看到,空白的为文档(document),粉色为 father 盒子,紫色为 son 盒子。
当我们点击空白处,就会弹出 document
当我们点击粉色处,就弹出 father,接着弹出 document
当我们点击紫色处,就弹出 son ,接着弹出 father, 最后弹出 document
总结:
其实就是最底层是document,中间是 father 的盒子 ,顶层是 son 的盒子,当我们点击了 son 盒子部分时,其实也就点击了 father document 这些盒子,就会触发对应的处理程序。
所以呢,冒泡有时候很打扰到我们,我们需要阻止冒泡。
我们将 e.stopPropagation(); 添加到 son 触发事件处理程序中,注意 function() 中写入 e
son.addEventListener('click', function(e) {
alert('son');
e.stopPropagation(); // stop 停止 Propagation 传播
}, false);
然后再次运行程序,点击 son 这个盒子的时候,就只会弹出 son。但是点击 father 的时候,会弹出father 接着弹出 document。它只阻止所在对象的冒泡。