阻止冒泡的两种方式
事件冒泡:开始时由最具体的元素接受,然后逐级向上传播到DOM最顶层节点。
e.stopPropagation(); && e.cancelBubble=true; 阻止冒泡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin:0;padding:0;}
.father{width:400px;height:400px;background:pink;margin:50px auto 0;}
.son{width:200px;height:200px;background:#454554;}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
var son=document.querySelector(".son");
var father=document.querySelector(".father");
//addEventListener() 第三个参数为true 是捕获 为false 是冒泡
son.addEventListener("click",function(e){
alert("son");
// e.stopPropagation();//阻止冒泡
// e.cancelBubble=true;//阻止冒泡 非标准
//阻止事件冒泡的兼容性解决方案
if(e && e.stopPropagation){
e.stopPropation();
}else{
window.event.cancelBubble=true;
}
},false);
father.addEventListener('click',function(e){
alert("father")
},false);
</script>
</body>
</html>