共计 2051 个字符,预计需要花费 6 分钟才能阅读完成。
捕获模式
addEventListener 的第三个参数 useCapture 为 true 则为捕获模式点击 C 时事件触发顺序为 A -> B -> C
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title></title>
<style>
.a {
background: lightblue;
padding: 50px;
}
.b {
background: lightgray;
padding: 50px;
}
.c {
background: lightyellow;
padding: 50px;
}
</style>
</head>
<body>
<div class=”a”>
A
<div class=”b”>
B
<div class=”c”>
C
</div>
</div>
</div>
</body>
<script>
var a = document.querySelector(‘.a’)
var b = document.querySelector(‘.b’)
var c = document.querySelector(‘.c’)
a.addEventListener(‘click’, function(event){
console.log(‘capture click a’)
}, true)
b.addEventListener(‘click’, function(event){
console.log(‘capture click b’)
}, true)
c.addEventListener(‘click’, function(event){
console.log(‘capture click c’)
}, true)
</script>
</html>
冒泡模式
不填写 addEventListener 的第三个参数为冒泡模式点击 C 时事件触发顺序为 C -> B -> A
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title></title>
<style>
.a {
background: lightblue;
padding: 50px;
}
.b {
background: lightgray;
padding: 50px;
}
.c {
background: lightyellow;
padding: 50px;
}
</style>
</head>
<body>
<div class=”a”>
A
<div class=”b”>
B
<div class=”c”>
C
</div>
</div>
</div>
</body>
<script>
var a = document.querySelector(‘.a’)
var b = document.querySelector(‘.b’)
var c = document.querySelector(‘.c’)
a.addEventListener(‘click’, function(event){
console.log(‘Bubble click a’)
})
b.addEventListener(‘click’, function(event){
console.log(‘Bubble click b’)
})
c.addEventListener(‘click’, function(event){
console.log(‘Bubble click c’)
})
</script>
</html>
取消冒泡
// 取消冒泡
event.cancelBubble = true
取消冒泡后事件就不会往上层传递
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title></title>
<style>
.a {
background: lightblue;
padding: 50px;
}
.b {
background: lightgray;
padding: 50px;
}
.c {
background: lightyellow;
padding: 50px;
}
</style>
</head>
<body>
<div class=”a”>
A
<div class=”b”>
B
<div class=”c”>
C
</div>
</div>
</div>
</body>
<script>
var a = document.querySelector(‘.a’)
var b = document.querySelector(‘.b’)
var c = document.querySelector(‘.c’)
a.addEventListener(‘click’, function(event){
console.log(‘Bubble click a’)
})
b.addEventListener(‘click’, function(event){
console.log(‘Bubble click b’)
})
c.addEventListener(‘click’, function(event){
console.log(‘Bubble click c’)
event.cancelBubble = true
})
</script>
</html>