DOM事件流存在三个阶段:捕获阶段,处于目标阶段,事件冒泡阶段。
处理事件顺序:捕获–>>目标–>冒泡
来看下面的示例理解什么是 捕获阶段,目标阶段,冒泡阶段。
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
#parent{
width: 200px;
height: 200px;
text-align: center;
line-height:3;
background: red;
}
#child{
width: 100px;
height: 100px;
margin: auto;
background: green;
}
</style>
</head>
<body>
<div id="parent">
parent
<div id="child">
child
</div>
</div>
</body>
可以看到 以上的html, id=parnt 和id=child 是父子关系。
(即child也是parent的一部分)
此时如果 parent和child有捕获事件和冒泡事件:
执行的顺序是:
1.点击绿色部分: parent的捕获–>child的捕获/child的目标阶段(谁先执行取决于那块代码在前)—冒泡—>parent的目标。
捕获顺序:由外到内(由父到子)。
冒泡顺序:由内到内(由子到父)。
先来看用于事件绑定的方法:
addEventListener(Event,listener,useCapture)
Event:事件类型,不带on(点击事件:click)
listener:事件监听函数
usrCapture:是否捕获,默认为false,不捕获。
capture:捕获
attachEvent(Event,listener)
Event:事件类型 带on(点击事件:onClick)
listener:监听函数
//attachEvent:IE10以下支持,IE11已经被废除。
冒泡事件:
示例1
<script type="text/javaScript">
var parent=document.getElementById("parent");
var child=document.getElementById("child");
parent.addEventListener("click",function(e){
console.log("parent");
},false)
child.addEventListener("click",function(e){
console.log("parent");
},false)
</script>
点击绿色区域输出:
child
parent
点击红色区域:
parent
在实际开发中,我们会有需求不想冒泡,使用
Even.stopPropagation()
示例2
<script type="text/javaScript">
var parent=document.getElementById("parent");
var child=document.getElementById("child");
parent.addEventListener("click",function(e){
console.log("parent");
},false)
child.addEventListener("click",function(e){
console.log("parent");
e.stopPropagation();
},false)
</script>
点击绿色区域:
child
点击红色区域:
parent
捕获事件:
示例3:
<script type="text/javascript">
var parent = document.getElementById("parent");
var child = document.getElementById("child");
parent.addEventListener("click", function(e) {
console.log("parent");
}, false);
child.addEventListener("click", function(e) {
console.log("捕获child");
}, true);
child.addEventListener("click", function(e) {
console.log("child");
}, false);
parent.addEventListener("click", function(e) {
console.log("捕获parent");
}, true);
</script>
点击绿色区域:
捕获parent
捕获child
child
parent
点击红色区域:
parent
捕获parent
点击红色区域的结果因为: 当一个节点同时有捕获和不捕获,那谁在前则执行谁。
你可试着改变上面js的代码顺序,看看结果。