直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="five">555
<div id="four">444
<div id="three">333
<div id="two">222
<div id="one">111
</div>
</div>
</div>
</div>
</div>
</body>
<script>
document.getElementById('five').addEventListener('click', function(){
alert('5')
})
document.getElementById('four').addEventListener('click', function(){
alert('4')
})
document.getElementById('three').addEventListener('click', function(){
alert('3')
}, true)
document.getElementById('two').addEventListener('click', function(){
alert('2')
})
document.getElementById('one').addEventListener('click', function(){
alert('1')
})
</script>
</html>
<style>
#five {
width: 200px;
height: 200px;
border: 2px solid black;
}
#four {
width: 150px;
height: 150px;
border: 2px solid black;
}
#three {
width: 100px;
height: 100px;
border: 2px solid black;
}
#two {
width: 70px;
height: 70px;
border: 2px solid black;
}
#one {
width: 30px;
height: 30px;
border: 2px solid black;
}
</style>
第一,把第三个参数都设成false(即默认)
点击three, alert的结果是3 4 5,冒泡
点击two, alert的结果是 2 3 4 5,冒泡。顺序冒泡
第二,把第三个参数都设成true
点击three, alert的结果是5 4 3,捕获
点击two, alert的结果是 5 4 3 2,捕获。顺序捕获
第三,只把第三个参数设成true, 如代码所示
点击three, alert的结果是3 4 5
点击two, alert结果是3 2 4 5
点击two, alert结果是 3 1 2 4 5,这个最经典。试试咯