阻止事件冒泡
可以使用e.stopPropagation()来阻止冒泡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
display: flex;
align-items: center;
margin: 0 auto;
width: 400px;
height: 400px;
background-color: aqua;
}
.son {
margin: 0 auto;
width: 200px;
height: 200px;
background-color: blue;
text-align: center;
}
</style>
</head>
<body>
<div class="father">
<div class="son">
点击son
</div>
</div>
<script>
var sNode = document.querySelector('.son');
sNode.addEventListener('click', function(e) {
alert('son');
// 阻止冒泡;不阻止冒泡的话还会继续往father层继续执行
e.stopPropagation();//不考虑兼容性 阻止冒泡方法1
e.cancelBubble = true; //兼容性 阻止冒泡方法2
})
var fNode = document.querySelector('.father');
fNode.addEventListener('click', function() {
alert('father');
})
</script>
</body>
</html>
该文章演示了如何在JavaScript中使用`e.stopPropagation()`方法阻止事件从子元素向父元素传播。当在子元素上点击时,调用此方法将防止事件冒泡到父元素,从而避免了父元素的事件处理函数被触发。示例代码展示了在一个包含父子元素的布局中,点击子元素只会触发子元素的事件,而不会触发父元素的事件。

743

被折叠的 条评论
为什么被折叠?



