W3C事件模型中事件捕捉和事件冒泡的执行顺序

前两天看到一道面试题说如果给一个DOM元素既添加单击操作的事件捕捉回调函数,也添加事件冒泡的回调函数,问先调用哪一个?

自己做了一个简单的测试程序进行验证。测试环境:chrome: Version 33.0.1750.154 m

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">

function initialize() {
var father = document.getElementById("father");

father.addEventListener("click", function () {
alert("Click event is bubbled.father is clicked.");
}, false);

father.addEventListener("click", function () {
alert("Click event is captured.father is clicked.");
}, true);

}
</script>
</head>
<body onload="initialize()" >
<div id="grandFather" style="position:relative; background: #ffd800;width:300px;height:300px;">
<p>grandFather</p>
<div id="father" style="position:absolute; background: #4cff00;width:200px;height:200px;left:50px;top:50px;" >
<p>father</p>
<div id="child" style="position:absolute; background: #0094ff;width:100px;height:100px;left:50px;top:50px;">
<p>child</p>
</div>
</div>
</div>
</body>
</html>

布局如下:

 

通过测试发现,点击不同的元素得到的结果并不一样。

1. 当点击"child"元素是得到的结果如下:

结论:当单击事件发生在子元素时,先触发父元素的Capture回调,然后是Bubble回调。也就是说,事件应该是先进行事件的捕捉,再进行事件的冒泡。

2. 但单击"parent"元素时,得到的结果如下:

结论:当单击事件发生在绑定事件的DOM元素时,回调函数的响应顺序似乎不确定。我尝试多次单击测试,有时候是先Captured, 有时候是先冒泡。

没有发现规律,希望高人赐教。

3. 当单击"grandFather"元素时,没有事件回调函数被调用。

 

 

posted @ 2014-04-02 17:45  临风远望  阅读(468)  评论(0编辑  收藏  举报