當同一個容器綁定兩個事件,遵循先捕獲,後冒泡 ,有一個前提是 點擊的事件先執行
<!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>
<style>
.box{
width: 300px;
height: 300px;
background: red;
}
.content{
width: 200px;
height: 200px;
background: green;
}
.wrapper{
width: 100px;
height: 100px;
background: yellow;
}
</style>
</head>
<body>
<div class="box">
<div class="content">
<div class="wrapper">
</div>
</div>
</div>
<script>
let box = document.getElementsByClassName("box")[0];
let content = document.getElementsByClassName("content")[0];
let wrapper = document.getElementsByClassName("wrapper")[0];
wrapper.addEventListener('click',function(){
console.log('wrapper')
},true)
content.addEventListener('click',function(){
console.log('content')
},true)
box.addEventListener('click',function(){
console.log('box')
},true)
wrapper.addEventListener('click',function(){
console.log('wrapperBubble')
},false)
content.addEventListener('click',function(){
console.log('contentBubble')
},false)
box.addEventListener('click',function(){
console.log('boxBubble')
},false)
</script>
</body>
</html>
調換位置,冒泡的處理事件在前
<!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>
<style>
.box{
width: 300px;
height: 300px;
background: red;
}
.content{
width: 200px;
height: 200px;
background: green;
}
.wrapper{
width: 100px;
height: 100px;
background: yellow;
}
</style>
</head>
<body>
<div class="box">
<div class="content">
<div class="wrapper">
</div>
</div>
</div>
<script>
let box = document.getElementsByClassName("box")[0];
let content = document.getElementsByClassName("content")[0];
let wrapper = document.getElementsByClassName("wrapper")[0];
wrapper.addEventListener('click',function(){
console.log('wrapperBubble')
},false)
content.addEventListener('click',function(){
console.log('contentBubble')
},false)
box.addEventListener('click',function(){
console.log('boxBubble')
},false)
wrapper.addEventListener('click',function(){
console.log('wrapper')
},true)
content.addEventListener('click',function(){
console.log('content')
},true)
box.addEventListener('click',function(){
console.log('box')
},true)
</script>
</body>
</html>