<!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>事件冒泡</title>
<style>
* {
margin: 0;
padding: 0;
}
#out_box {
width: 450px;
height: 450px;
background-color: #929854;
text-align: center;
position: absolute;
top: 100px;
left: 100px;
}
#inner_box {
width: 300px;
height: 300px;
background-color: #4365c3;
line-height: 75px;
position: absolute;
left: 75px;
top: 75px;
}
</style>
</head>
<body>
<div id="out_box">
<div id="inner_box">李昊哲</div>
</div>
</body>
</html>
<script>
let out_box = document.querySelector('#out_box');
out_box.addEventListener('click', function(e) {
alert('out_box');
});
let inner_box = document.querySelector('#inner_box');
inner_box.addEventListener('click', function(e) {
// ie下阻止冒泡
e.cancelBubbl = true;
// 其它浏览器下阻止冒泡
// 这是阻止事件的冒泡方法,不止事件向document上蔓延,但是默认事件任然会执行,当你调用这个方法的时候,如果点击一个连接,这个连接仍然会被打开
e.stopPropagation();
// 这是阻止默认事件的方法,调用此方法时,链接不会被打开,但是会发生冒泡,冒泡会传递到上一层的父元素
e.preventDefault();
alert('inner_box');
});
</script>
阻止事件冒泡
于 2022-09-16 10:26:14 首次发布