zoukankan      html  css  js  c++  java
  • javascript event bubbling and capturing (再谈一谈js的事件冒泡和事件补获,看到这篇文章加深了理解)

    原文地址:http://javascript.info/tutorial/bubbling-and-capturing

    先给出最终的结论:

    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.

    bubbling:

      

    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.

    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:

    <!DOCTYPE HTML>
    <html>
    <body>
    <link type="text/css" rel="stylesheet" href="example.css">
    
    <div class="d1">1  <!-- the topmost -->
        <div class="d2">2
            <div class="d3">3 <!-- the innermost -->
            </div> 
        </div>
    </div>
    
    </body>
    </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.

    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.

    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.
  • 相关阅读:
    eclipse svn插件
    eclipse 图片预览插件
    eclipse properties文件插件
    eclipse Failed to load the JNIshared library
    Spark MLlib之线性回归源代码分析
    ul,li不能左右居中的问题
    【日常学习】【搜索/递归】codevs2802 二的幂次方题解
    UVa 112
    查询一个月最后一天的总用户数,数据库中没有保存最好一天的数据,就查询本月数据库已存有的最后一天的数据
    uva:10763
  • 原文地址:https://www.cnblogs.com/oxspirt/p/4449583.html
Copyright © 2011-2022 走看看