HTML DOM元素的事件的Bubbling 和 Capturing

来源:互联网 发布:linux shell 权限不够 编辑:程序博客网 时间:2024/04/28 05:38

Bubbling and capturing

  1. Bubbling
    1. this and event.target
    2. Stopping the bubbling
  2. Capturing
  3. Summary

DOM elements can be nested inside each other. And somehow, the handler of the parent works even if you click on it’s child.

The reason is event bubbling.

For example, the following DIV handler runs even if you click a nested tag like EM or CODE:

<div onclick="alert('Div handler worked!')">
  <em>Click here triggers on nested <code>EM</code>, not on <code>DIV</code></em>
</div>

That’s because an event bubbles from the nested tag up and triggers the parent.

Bubbling

The main principle of bubbling states:
After an event triggers on the deepest possible element, it then triggers on parents in nesting order.

For example, there are 3 nested divs:

01<!DOCTYPE HTML>
02<html>
03<body>
04<link type="text/css" rel="stylesheet" href="example.css">
05 
06<div class="d1">1  <!-- the topmost -->
07    <div class="d2">2
08        <div class="d3">3 <!-- the innermost -->
09        </div>
10    </div>
11</div>
12 
13</body>
14</html>

The bubbling guarantees that click on Div 3 will trigger onclick first on the innermost element 3 (also caled the target), then on the element 2, and the last will be element 1.

Bubbling events order

The order is called a bubbling order, because an event bubbles from the innermost element up through parents, like a bubble of air in the water.

Click below to see it bubble:

Open the code in new window

this and event.target

The deepest element which triggered the event is called the target or, the originating element.

Internet Explorer has the srcElement property for it, all W3C-compliant browsers use event.target. The cross-browser code is usually like this:

var target = event.target || event.srcElement

When handlers trigger on parents:

  • event.target/srcElement - remains the same originating element.
  • this - is the current element, the one event has bubbled to, the one which runs the handler.

Bubbling events order

In the example below, each DIV has an onclick handler which outputs both target and this.

Click on a div.

Note that:

  • the target is constant through all bubbling process,
  • this changes and gets highlighted.

Open the code in new window

In W3C-compliant browsers this is also available as event.currentTarget.

attachEvent does not pass this or event.currentTarget at all.

Stopping the bubbling

The bubbling goes right to the top. When an event occurs on an element - it will bubble up to <HTML>, triggering handlers on it’s way.

But a handler may decide that event is fully processed and stop the bubbling.

The code is:

  • For W3C-compliant browsers:
    event.stopPropagation()
  • For IE<9:
    event.cancelBubble = true

The cross-browser-code:

01element.onclick = function(event) {
02    event = event || window.event // cross-browser event
03     
04    if (event.stopPropagation) {
05        // W3C standard variant
06        event.stopPropagation()
07    else {
08        // IE variant
09        event.cancelBubble = true
10    }
11}

There is a one-lined variant too:

event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true)

If the element has several handlers on same event, then handlers are independent. All of them get executed..

For example, if there are two onclick handlers on the same link, then stopping bubbling in one of them has no effect on the other one. Also, the browser doesn’t guarantee the order in which they trigger.

Capturing

In all browsers, except IE<9, there are two stages of event processing.

The event first goes down - that’s called capturing, and then bubbles up. This behavior is standartized in W3C specification.

W3C events order

According to this model, the event:

  1. Captures down - through 1 -> 2 -> 3.
  2. Bubbles up - through 3 -> 2 -> 1.

All methods of event handling ignore the caputiring phase. Using addEventListener with last argumenttrue is only the way to catch the event at capturing.

elem.addEventListener( type, handler, phase )

phase = true
The handler is set on the capturing phase.
phase = false
The handler is set on the bubbling phase.

Click in a div below to see capturing in action (no IE<9):

It should be 1 -> 2 -> 3.

Source JavaScript of the example:

1var divs = document.getElementsByTagName('div')
2 
3for(var i=0; i<divs.length; i++) {
4  divs[i].addEventListener("click", highlightThis, true)
5}

Click to open in the playground: tutorial/browser/events/bubbling/capture/index.html.

In real-life the capturing phase is rarely used. But..
There are events which don’t bubble, but can be captured. For example,onfocus/onblur.

Now let’s assign handlers at both stages.

Click on a div below to see the event processing order (no IE<9):

It should be 1 -> 2 -> 3 -> 3 -> 2 -> 1.

Source JavaScript of the example:

1var divs = document.getElementsByTagName('div')
2 
3for(var i=0; i<divs.length; i++) {
4  divs[i].addEventListener("click", highlightThis, true)
5  divs[i].addEventListener("click", highlightThis, false)
6}

Click to open in the playground: tutorial/browser/events/bubbling/both/index.html.

Summary

  • Events first are captured down to deepest target, then bubble up. In IE<9 they only bubble.
  • All handlers work on bubbling stage excepts addEventListener with last argument true, which is the only way to catch the event on capturing stage.
  • Bubbling/capturing can be stopped by event.cancelBubble=true (IE) orevent.stopPropagation() for other browsers.

Source:
http://javascript.info/tutorial/bubbling-and-capturing
原创粉丝点击