ThatManK Mobile Article
阻止冒泡
阻止冒泡事件
<!DOCTYPE html>
<html lang="en">
<head>
<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>
// 常见事件对象的属性和方法
var son = document.querySelector(".son");
var father = document.querySelector(".father");
// 阻止冒泡 dom 推荐的标准 stopPropagation()
son.addEventListener(
"click",
function (e) {
alert("son");
e.stopPropagation(); // stop 停止 Propagation 传播
// e.cancelBubble = true; // 非标准 cancel 取消 bubble 泡泡
},
false
);
father.addEventListener(
"click",
function () {
alert("father");
},
false
);
document.addEventListener("click", function () {
alert("document");
});
</script>
</body>
</html>