现在,我们看看捕获和冒泡的区别:
捕获:从最外层的祖先元素,向目标元素进行事件的捕获,但是默认此时不会触发事件
冒泡: 事件从目标元素向他的祖先元素传递,依次触发祖先元素上的事件
我们将这个图可以看到了,先执行捕获的过程,当捕获到目标元素上的触发事件,接着开始冒泡。但是这个单纯的冒泡又有区别。我们先看下这种情况下的,时间会从目标元素向他的祖先元素传递,最后触发的是从祖先元素到目标元素。
那我们在代码里该怎么设置呢?代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例046</title>
<style>
#box1 {
width: 300px;
height: 300px;
background-color: yellowgreen;
margin: 20px auto;
position: relative;
}
#box2 {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
left: 50px;
top: 50px;
}
#box3 {
width: 150px;
height: 150px;
background-color: skyblue;
position: absolute;
left: 25px;
top: 25px;
}
</style>
<script>
window.onload = function () {
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
/*
box1.onclick = function(){
alert("1");
}
box2.onclick = function(){
alert("2");
}
box3.onclick = function(){
alert("3");
}
*/
bindBox(box1, "click", function () {
alert("祖父box1--------1");
})
bindBox(box2,"click",function(){
alert("父亲box2--------2");
})
bindBox(box3,"click",function(){
alert("儿子box3--------3")
})
function bindBox(obj, eventStr, callback) {
if (obj.addEventListener) {
//大部分浏览器兼容的方式
obj.addEventListener(eventStr, callback, true);
} else {
/*
* this是谁由调用方式决定
* callback.call(obj)
*/
//IE8及以下
obj.attachEvent("on" + eventStr, function () {
//在匿名函数中调用回调函数
callback.call(obj);
});
}
}
}
</script>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3"></div>
</div>
</div>
</body>
</html>
弹出的弹窗顺序依次向下。
如果希望在捕获阶段就触发事件,可以将addEventListener()的第三个参数设置为true,一般情况下我们不会希望在捕获阶段触发事件,所以这个参数一般都是false, IE8及以下的浏览器中没有捕获阶段。