DOM事件标准定义了两种事件流,这两种事件流有着显著的不同并且可能对你的应用有着相当大的影响。这两种事件流分别是捕获和冒泡。和许多Web技术一样,在它们成为标准之前,Netscape和微软各自不同地实现了它们。Netscape选择实现了捕获事件流,微软则实现了冒泡事件流。幸运的是,W3C决定组合使用这两种方法,并且大多数新浏览器都遵循这两种事件流方式。
事实上,捕获阶段是一个和冒泡阶段完全相反的过程,即事件由祖先元素向子元素传播,和一个石子儿从水面向水底下沉一样,要说明的是在 IE,opera浏览器中,是不存在这个阶段的。从各浏览器提供的注册事件监听的方法中可见一斑,例如适用于ie,opera的attachEvent, 有两个参数,attachEvent(”on”+type,fn),而适用于所谓标准浏览器的addEventListener则有三个参 数,addEventListener(type,fn,boolean),前面两个参数不用解释,第三个参数boolean,就是决定注册事件发生在捕 获阶段还是冒泡阶段
demo:
<span style="font-size:14px;"><strong><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
body{margin:0;}
*{
text-align: right;
}
#one{
width:500px;
height:300px;
background:rgb(255,0,0);
}
#two{
width:400px;
height:260px;
background:rgb(255,50,50);
}
#three{
width:300px;
height:240px;
background:rgb(255,100,100);
}
#four{
width:200px;
height:200px;
background:rgb(255,150,150);
}
</style>
</head>
<body>
<div id='one'>one
<div id='two'>two
<div id='three'>three
<div id='four'>four
</div>
</div>
</div>
</div>
<script>
var one = document.getElementById('one');
var two = document.getElementById('two');
var three = document.getElementById('three');
var four = document.getElementById('four');
var useCapture = false; //默认为false; false为冒泡获取【目标元素先触发】 true为捕获获取【父级元素先触发】
one.addEventListener('click', function() {
console.log('one');
}, useCapture);
two.addEventListener('click', function() {
console.log('two');
}, useCapture);
three.addEventListener('click', function(e) {
// e.stopPropagation();
console.log('three');
}, useCapture);
four.addEventListener('click', function() {
console.log('four');
}, useCapture);
/*
false
冒泡
点击four div
输出结果:four three two one
true
捕获
点击four div
输出结果: one two three four
*/
</script>
</body>
</html></strong></span>