What is event bubbling and capturing?

答案1

Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

With capturing, the event is first captured by the outermost element and propagated to the inner elements.

Capturing is also called "trickling", which helps remember the propagation order:

trickle down, bubble up   向下滴水,向上冒泡

Back in the old days, Netscape advocated event capturing, while Microsoft promoted event bubbling. Both are part of the W3C Document Object Model Events standard (2000).

IE < 9 uses only event bubbling, whereas IE9+ and all major browsers support both. On the other hand, the performance of event bubbling may be slightly lower for complex DOMs.

We can use the addEventListener(type, listener, useCapture) to register event handlers for in either bubbling (default) or capturing mode. To use the capturing model pass the third argument as true.

Example

<div>
<ul>
<li></li>
</ul>
</div>

In the structure above, assume that a click event occurred in the li element.

In capturing model, the event will be handled by the div first (click event handlers in the div will fire first), then in the ul, then at the last in the target element, li.

In the bubbling model, the opposite will happen: the event will be first handled by the li, then by the ul, and at last by the div element.

For more information, see

In the example below, if you click on any of the highlighted elements, you can see that the capturing phase of the event propagation flow occurs first, followed by the bubbling phase.

var logElement = document.getElementById('log');

function log(msg) {
logElement.innerHTML += ('<p>' + msg + '</p>');
} function capture() {
log('capture: ' + this.firstChild.nodeValue.trim());
} function bubble() {
log('bubble: ' + this.firstChild.nodeValue.trim());
} var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', capture, true);
divs[i].addEventListener('click', bubble, false);
}
p {
line-height: 0;
} div {
display:inline-block;
padding: 5px; background: #fff;
border: 1px solid #aaa;
cursor: pointer;
} div:hover {
border: 1px solid #faa;
background: #fdd;
}
<div>1
<div>2
<div>3
<div>4
<div>5</div>
</div>
</div>
</div>
</div>
<section id="log"></section>
 

Another example at JSFiddle.

Event Flow

3. DOM Event Architecture

This section is non-normative. Refer to [DOM] for a normative description of the DOM event architecture

3.1. Event dispatch and DOM event flow

This section gives a brief overview of the event dispatch mechanism and describes how events propagate through the DOM tree.

Applications can dispatch event objects using the dispatchEvent() method, and the event object will propagate through the DOM tree as determined by the DOM event flow.

Event objects are dispatched to an event target. But before dispatch can begin, the event object’s propagation path must first be determined.

The propagation path is an ordered list of current event targets through which the event passes. This propagation path reflects the hierarchical tree structure of the document. The last item in the list is the event target, and the preceding items in the list are referred to as the target’s ancestors, with the immediately preceding item as the target’s parent.

Once the propagation path has been determined, the event object passes through one or more event phases. There are three event phases: capture phasetarget phase and bubble phase. Event objects complete these phases as described below. A phase will be skipped if it is not supported, or if the event object’s propagation has been stopped. For example, if the bubbles attribute is set to false, the bubble phase will be skipped, and if stopPropagation() has been called prior to the dispatch, all phases will be skipped.

  • The capture phase: The event object propagates through the target’s ancestors from the Window to the target’s parent. This phase is also known as the capturing phase.

  • The target phase: The event object arrives at the event object’s event target. This phase is also known as the at-target phase. If the event type indicates that the event doesn’t bubble, then the event object will halt after completion of this phase.

  • The bubble phase: The event object propagates through the target’s ancestors in reverse order, starting with the target’s parent and ending with the Window. This phase is also known as the bubbling phase.

扩展阅读

Bubbling and capturing

What is event bubbling and capturing?的更多相关文章

  1. javascript event bubbling and capturing (再谈一谈js的事件冒泡和事件补获,看到这篇文章加深了理解)

    原文地址:http://javascript.info/tutorial/bubbling-and-capturing 先给出最终的结论: Summary Events first are captu ...

  2. 事件冒泡(event bubbling)与事件捕捉(event capturing)

    事件捕捉: 单击<div>元素就会以下列顺序触发click 事件. Document => Element html => Element body => Element ...

  3. js event bubble and capturing

    Bubble: pppppp Capturing pppppp Mix pppppp To Stop Bubble pppppp // JS Bin

  4. How to correctly use preventDefault(), stopPropagation(), or return false; on events

    How to correctly use preventDefault(), stopPropagation(), or return false; on events I’m sure this h ...

  5. 事件(event),正则

    1.事件(event):事件是可以被 JavaScript 侦测到的行为.网页中的每个元素都可以产生某些可以触发 JavaScript 函数的事件.2.事件源: 触发事件的元素 事件: 被 JavaS ...

  6. HTML DOM Event对象

    我们通常把HTML DOM Event对象叫做Event事件 事件驱动模型 事件源:(触发事件的元素)事件源对象是指event对象 其封装了与事件相关的详细信息. 当事件发生时,只能在事件函数内部访问 ...

  7. Javascript Event

    事件原理 JS的事件原理,先看一段HTML. <html> <head> <title>Example</title> </head> &l ...

  8. 理解JavaScript中的事件处理 阻止冒泡event.stopPropagation();

    原文地址:http://www.cnblogs.com/binyong/articles/1750263.html 这篇文章对于了解Javascript的事件处理机制非常好,将它全文转载于此,以备不时 ...

  9. HTML:Event [转]

    这篇文章对于了解Javascript的事件处理机制非常好,将它全文转载于此,以备不时之需. 什么是事件? 事件(Event)是JavaScript应用跳动的心脏 ,也是把所有东西粘在一起的胶水.当我们 ...

随机推荐

  1. Sqrt Bo (水题)

    #include<bits/stdc++.h> using namespace std; ], comp; ]; int main(){ arr[] = 1LL; ; i < ; i ...

  2. multiprocessing 源码解析 更新中......

    一.参考链接 1.源码包下载·链接:   https://pypi.org/search/?q=multiprocessing+ 2.源码包 链接:https://pan.baidu.com/s/1j ...

  3. Lua 判断表是否为空方法

    [1]判断表为空的方法 目前为止,Lua语言中判断table表是否为空有三种方式: (1)#table,当table为数组时直接返回table表的长度. (2)当table是字典时,返回table的长 ...

  4. mark_save

    class BookConfig(ModelStark): def edit(self, obj=None, is_header=False): if is_header: return " ...

  5. (Review cs231n)loss function and optimization

    分类器需要在识别物体变化时候具有很好的鲁棒性(robus) 线性分类器(linear classifier)理解为模板的匹配,根据数量,表达能力不足,泛化性低:理解为将图片看做在高维度区域 线性分类器 ...

  6. 【Alpha版本】冲刺阶段——Day1

    [Alpha版本]冲刺阶段--Day1 阅读目录 Alpha 阶段成员分工及任务量 团队成员贡献值的计算规则 明日任务 今日贡献量 站立式会议 TODOlist [Alpha 阶段成员分工及任务量] ...

  7. case when then的用法

    用法一:等值判断,相当于switch CASE expression WHEN value1 THEN returnValue1 WHEN value2 THEN returnValue2 WHEN ...

  8. ARQC与ARPC的生成和校验方法

    转载:https://www.cnblogs.com/ttss/p/4364328.html ARQC:authenticate request cryptogram,授权请求报文 ARPC:auth ...

  9. byte以及UTF-8的转码规则

    https://www.cnblogs.com/hell8088/p/9184336.html 多年来闲麻烦,只记录笔记,不曾编写BLOG,本文为原创,如需转载请标明出处 废话不说,直奔主题 asci ...

  10. python 之xml.etree.ElementTree

    Element类型是一种灵活的容器对象,用于在内存中存储结构化数据. [注意]xml.etree.ElementTree模块在应对恶意结构数据时显得并不安全. 每个element对象都具有以下属性: ...