简单解析事件捕捉
上篇博客说到了事件冒泡,其实在JavaScript中,说到事件冒泡还有两个个不得不提的事件捕获和默认事件,我们先来说一下事件捕获。效果如下图:
HTML代码:
<div class="box1">
<div class="box2">
<div class="box3">
<div class="box4"></div>
</div>
</div>
</div>
CSS代码:
* {
margin: 0;
padding: 0;
}
.box1 {
width: 400px;
height: 400px;
background: red;
}
.box2 {
width: 300px;
height: 300px;
background: yellow;
}
.box3 {
width: 200px;
height: 200px;
background: skyblue;
}
.box4 {
width: 100px;
height: 100px;
background: green;
}
JS代码:
// 04事件捕捉
// addEventListener("事件",function(){},fasle(默认,事件冒泡阶段执行)/true)
// 事件监听
var oBox1=document.getElementsByClassName("box1")[0];
var oBox2=document.getElementsByClassName("box2")[0];
var oBox3=document.getElementsByClassName("box3")[0];
var oBox4=document.getElementsByClassName("box4")[0];
oBox1.addEventListener("click",function(ev){
var ev=ev||window.event;
console.log("box1");
// alert("box1");
},true)
oBox2.addEventListener("click",function(ev){
var ev=ev||window.event;
console.log("box2");
// alert("box1");
},true)
oBox3.addEventListener("click",function(ev){
var ev=ev||window.event;
console.log("box3");
// alert("box1");
},true)
oBox4.addEventListener("click",function(ev){
var ev=ev||window.event;
console.log("box4");
// alert("box1");
},true)
视频讲解链接:
https://www.bilibili.com/video/BV1Ag4y1q7YB/