简介
false是冒泡过程,true是捕获过程
默认值是false
从内往外执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box3{
width:200px;
height:200px;
background-color:aqua;
}
#box2{
background-color:pink;
width: 300px;
height:300px;
}
#box1{
background-color:blue;
width:400px;
height:400px;
}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3">
</div>
</div>
</div>
<script>
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
var bbbb = document.getElementById("bbbb");
box1.addEventListener("click",function(){
console.log(this.id);
});
box2.addEventListener("click",function(){
console.log(this.id);
});
box3.addEventListener("click",function(){
console.log(this.id);
});
</script>
</body>
</html>
从外往内执行
原函数后面添加,true
变成从外往内执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box3{
width:200px;
height:200px;
background-color:aqua;
}
#box2{
background-color:pink;
width: 300px;
height:300px;
}
#box1{
background-color:blue;
width:400px;
height:400px;
}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3">
</div>
</div>
</div>
<script>
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
var bbbb = document.getElementById("bbbb");
box1.addEventListener("click",function(){
console.log(this.id);
},true);
box2.addEventListener("click",function(){
console.log(this.id);
},true);
box3.addEventListener("click",function(){
console.log(this.id);
},true);
</script>
</body>
</html>
从外向内再从内向外执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box3{
width:200px;
height:200px;
background-color:aqua;
}
#box2{
background-color:pink;
width: 300px;
height:300px;
}
#box1{
background-color:blue;
width:400px;
height:400px;
}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3">
</div>
</div>
</div>
<script>
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
var bbbb = document.getElementById("bbbb");
box1.addEventListener("click",function(){
console.log(this.id);
},true);
box2.addEventListener("click",function(){
console.log(this.id);
},true);
box3.addEventListener("click",function(){
console.log(this.id);
},true);
box1.addEventListener("click",function(){
console.log(1);
},false);
box2.addEventListener("click",function(){
console.log(2);
},false);
box3.addEventListener("click",function(){
console.log(3);
},false);
</script>
</body>
</html>