事件冒泡:如果出现嵌套关系,并且嵌套的元素都有相同的事件,那么当我们操作子元素的时候,会像父级元素一层一层传递
事件捕获:与事件捕获相反
<!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 type="text/css">
* {
margin: 0;
padding: 0;
}
.a1 {
width: 400px;
height: 400px;
background-color: red;
}
.a2 {
width: 300px;
height: 300px;
background-color: pink;
}
.a3 {
width: 200px;
height: 200px;
background-color: blue;
}
</style>
</head>
<body>
<div class="a1">
<div class="a2">
<div class="a3"></div>
</div>
</div>
<script>
let a1 = document.querySelector('.a1'),
a2 = document.querySelector('.a2'),
a3 = document.querySelector('.a3')
a1.addEventListener(
'click',
function () {
console.log('a1')
},
false
)
a2.addEventListener(
'click',
function () {
console.log('a2')
},
false
)
a3.addEventListener(
'click',
function () {
console.log('a3')
},
false
)
</script>
</body>
</html>
所以当我们点a3的时候会打印a3,a2,a1,
取消冒泡
// 取消冒泡
function cancelBubble(e) {
var e = e || event
if (e.stopPropagation) {
e.stopPropagation()
} else {
e.cancelBubble = true
}
}
//Event.cancelBubble 属性是 Event.stopPropagation()的一个曾用名。在从事件处理程序返回之前将其值设置为 true 可阻止事件的传播。
取消默认事件(我们定义的事件)
e.preventDefault()