一、事件冒泡
在浏览器客户端应用平台,基本上都是以事件驱动的,就是说去执行某个事件,然后做出相应的操作。
事件冒泡就是在事件开始时,由最具体的元素(文档中最底层的那个节点)接受,然后逐级向上传播到最不具体的节点(文档)。比如说,在一个页面有一个div元素,加上一个点击事件,在点击事件触发的时候,它的传递过程就是由div→body→html→document(老版本暂且不谈),它会沿着DOM树逐级的传递。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.outer{
width: 200px;
height: 200px;
background: red;
z-index: 1;
}
.cent{
width: 100px;
height: 100px;
background: blue;
position: absolute;
right: 0;
left: 0;
bottom: 0;
top: 0;
margin:auto;
z-index: 2;
}
.insert{
width: 50px;
height: 50px;
background: orange;
position: absolute;
right: 0;
left: 0;
bottom: 0;
top: 0;
margin:auto;
z-index: 3;
}
div{
position: relative;
}
</style>
</head>
<body>
<div class="outer">
<div class="cent">
<div class="insert"></div>
</div>
</div>
</body>
<script type="text/javascript">
var Outer=document.getElementsByClassName("outer")[0];
var Cent=document.getElementsByClassName("cent")[0];
var Insert=document.getElementsByClassName("insert")[0];
var aBody=document.getElementsByTagName("body")[0];
Outer.onclick=function(){
console.log("aaa")
}
Cent.onclick=function(){
console.log("bbb")
}
Insert.onclick=function(){
console.log("ccc")
}
aBody.onclick=function(){
console.log("我是body")
}
</script>
</html>
在这个嵌套的层级关系中,点击Insert这个元素的时候会依次输出ccc、bbb、aaa、我是body,这就是事件冒泡机制。
二、阻止事件冒泡
阻止事件冒泡的方法有两种:
- storpPrapagation() // 不支持IE低版本
- cancelBubble=true
兼容写法:
if(event.storpPrapagation){
event.storpPrapagation();
}else{
cancelBubble=true;
}
还拿上面的举例:
<script type="text/javascript">
var Outer=document.getElementsByClassName("outer")[0];
var Cent=document.getElementsByClassName("cent")[0];
var Insert=document.getElementsByClassName("insert")[0];
var aBody=document.getElementsByTagName("body")[0];
Outer.onclick=function(e){
var evt=e||event;
evt.stopPropagation();
console.log("aaa")
}
Cent.onclick=function(){
console.log("bbb")
}
Insert.onclick=function(){
console.log("ccc")
}
aBody.onclick=function(){
console.log("我是body")
}
</script>
在outer元素上阻止冒泡,控制台输出的就只有ccc、bbb、aaa,而没有‘我是body’,就是因为冒泡事件在执行到outer元素的时候被阻止了,所以body并没有执行点击事件。
点滴的积累,最终会形成汪洋大海。