一、事件捕捉(Event Capture)的实现问题
首先在说这件事前,先感谢一下Realazy。
W3C DOM Level2的事件模型规范中,事件在DOM树中的传播过程(从根节点到目标节点)被分为了两个阶段:捕捉(Capture)和冒泡(Bubbling)。下面这个图能大概的说明整个过程:
(from W3C)
如果想创建一个捕捉事件,在支持W3C 事件模型的浏览器中,将addEventListener的第三个参数设为true就好了。例如:
document.getElementById('foo').addEventListener('click',function(){alert('Hello, world!');},true);
前一阵因为想弄懂事件捕捉,所以做了点小实验,分别在Firefox 2、Safari 3 on Windows和Opera 9上实践了事件捕捉(当然,因为IE不支持事件捕捉,所以…),实验的原理见下图:
ID为div1和div2的两个元素都被委派了捕捉阶段的事件处理函数,这样:
然而,以上的设想只试用于Firefox 2和Safari 3 on Windows,在Opera 9中,事情会变成这样:
可以看出,在Opera 9中,目标元素(TargetElement)的click事件没有被执行。通过Realazy(orz…)的指点,找到了这篇文章:《Event capture explained》,发现,
来Opera中的实现才是正确的。此文中有一段话如是说:
The DOM spec states that capturing events should not fire on target, because the idea of a capturing event is to detect events before they reach their targets. Because of bugs in Gecko and Safari, web content that is tested mostly with Firefox or other Gecko-based browsers sometimes expects capturing listeners to fire on target. Such content will fail in Opera 7, 8 and current releases of 9 because of its correct implementation of the standard.
大意是说:DOM规范中陈述了捕捉型的事件不应该在目标元素上被执行,因为捕捉型事件的用意就是为了监测到达目标元素之前的事件。Firefox和Safari的实现都是带有bug的。
再来看看W3C的DOM Events规范中的原话:
A capturing EventListener will not be triggered by events dispatched directly to the EventTarget upon which it is registered.
所以,在整个事件传播中,被执行的顺序是:
在了解了这些后,也许还是不要使用事件捕捉为妙,至少暂时不要。