一、基本概念
当祖先与后代元素的事件相同情况下
事件传播,分为三个阶段
- 捕获阶段:从最外层元素,向目标元素进行事件捕获,默认此时不触发事件
- 目标阶段:事件捕获到目标元素,捕获结束在目标元素上执行事件
- 冒泡阶段:事件从目标元素向它祖先元素传递,依次触发祖先元素上的事件
如图所示:
假如触发box3,上图便是box3事件传播的过程
二、代码实现上图
body代码
<body>
<div id="box1">
box1
<div id="box2">
box2
<div id="box3">box3</div>
</div>
</div>
</body>
CSS代码
<style type="text/css">
#box1{
width: 300px;
height: 300px;
background-color: yellowgreen;
padding: 20px;
text-align: center;
margin: 20px;
}
#box2{
width: 200px;
height: 200px;
background-color: yellow;
padding: 20px;
margin-top: 5px;
margin-left: 30px;
}
#box3{
width: 150px;
height: 150px;
background-color: skyblue;
margin-top: 5px;
margin-left: 25px;
}
</style>
JS代码
<script type="text/javascript">
window.onload = function(){
/**
* 分别为三个div绑定单击响应函数
*/
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
bind(box1,"click",function(){
alert("我是box1的函数")
})
bind(box2,"click",function(){
alert("我是box2的函数")
})
bind(box3,"click",function(){
alert("我是box3的函数")
})
}
//事件绑定函数
function bind(obj,eventStr,callback){
if(obj.addEventListener){
//大部分浏览器兼容的方式
obj.addEventListener(eventStr,callback,false);
}else{
//IE8及以下
obj.attachEvent("on"+eventStr,function(){
//在匿名函数中调用匿名函数
callback.call(obj);
});
}
}
</script>
需要说一下是:在捕获阶段,不触发事件,因此addEventListener方法第三个参数为false