事件的传播
事件传播分成了三个阶段
1.捕获阶段
在捕获阶段时从最外层的祖先元素,向目标元素进行事件的捕获,但是默认此时不会触发事件
2.目标阶段
事件捕获到目标元素,捕获结束开始在目标元素上触发事件
3.冒泡阶段
事件从目标元素向他的祖先元素传递,依次触发祖先元素上的事件
- 如果希望在捕获阶段就触发事件,可以将addEventListener()的第三个参数设置为true,一般情况下不会使用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
#box1{
width: 300px;
height: 300px;
background-color: pink;
}
#box2{
width: 200px;
height: 200px;
background-color: rgb(172, 80, 95);
}
#box3{
width: 150px;
height: 150px;
background-color: rgb(100, 9, 24);
}
</style>
<script>
window.onload= function(){
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, true);
}else{
// IE8及以下
obj.attachEvent("on"+eventStr, function(){
callback.call(obj);
});
// 修改this的方法:
// 在匿名函数中调用callback(),拿回函数的调用权
// 再通过call(对象)替换this
}
}
</script>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3">
</div>
</div>
</div>
</body>
</html>
点击box3
输出:
我是box1;
我是box2;
我是box3;
- IE8及以下的浏览器中没有捕获阶段