事件流
事件从最里面开始执行,一层一层向外,把这种现象称为事件流
事件流分为三类:事件冒泡、事件捕获、DOM事件流
(1)(默认的)冒泡事件:最开始由最具体的元素(文档中嵌套层次最深的那个节点)接收,然后逐级向上传播至最不具体的节点。简单来说就是从精准到模糊,从里向外(IE)
(2)(先发生)捕获事件:最开始由最不具体的元素接收,然后逐级向下传播至最具体的节点。简单来说从外到里(网景)
(3)DOM事件流:有三个阶段(捕获——目标——冒泡)
案例:
事件捕获
<style>
#one {
width: 200px;
height: 200px;
background-color: antiquewhite;
}
#two {
width: 100px;
height: 100px;
background-color: rgb(255, 145, 0);
}
#three {
width: 50px;
height: 50px;
background-color: rgb(117, 117, 117);
}
</style>
<div id="one">
<div id="two">
<div id="three"></div>
</div>
</div>
<script>
function $(id) {
return document.getElementById(id);
}
$("one").addEventListener("click",showM1,true);
$("two").addEventListener("click",showM2,true);
$("three").addEventListener("click",showM3,true);
function showM1(){
console.log(111);
}
function showM2(){
console.log(222);
}
function showM3(){
console.log(333);
}
</script>
案例:
事件冒泡
<style>
.one{
width: 200px;
height: 200px;
background-color: antiquewhite;
}
.two{
width: 100px;
height: 100px;
background-color: rgb(255, 145, 0);
}
.three{
width: 50px;
height: 50px;
background-color: rgb(117, 117, 117);
}
</style>
<div class="one">
<div class="two">
<div class="three"></div>
</div>
</div>
<script>
document.getElementsByClassName("one")[0].onclick=function(){
console.log(111);
}
document.getElementsByClassName("two")[0].onclick=function(){
console.log(222);
}
document.getElementsByClassName("three")[0].onclick=function(){
console.log(333);
let e=arguments[0]||window.event;
// e.stopPropagation(); //阻止冒泡 //DOM浏览器
// e.cancelBubble=true; //阻止冒泡 //IE<8
}
</script>