美文网首页
Bubbling and capturing

Bubbling and capturing

作者: TRYao | 来源:发表于2018-06-05 15:17 被阅读0次

    Let’s start with an example.
    This handler is assigned to <div>, but also runs if you click any nested tag like <em> or <code>:

    <div onclick="alert('The handler!')">
      <em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs.</em>
    </div>
    

    edit it on codepen
    Isn’t it a bit strange? Why the handler on <div> runs if the actual click was on <em>?

    Bubbling

    The bubbling principle is simple.
    When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
    Let’s say, we have 3 nested elements FORM > DIV > P with a handler on each of them:

    <style>
      body * {
        margin: 10px;
        border: 1px solid blue;
      }
    </style>
    
    <form onclick="alert('form')">FORM
      <div onclick="alert('div')">DIV
        <p onclick="alert('p')">P</p>
      </div>
    </form>
    

    edit it on codepen
    A click on the inner <p> first runs onclick:

    1. On that <p>.
    2. Then on the outer <div>.
    3. Then on the outer <form>.
    4. And so on upwards till the document object.

    So if we click on <p>, then we’ll see 3 alerts: p → div → form.

    The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.

    文章参考:Bubbling and capturing

    相关文章

      网友评论

          本文标题:Bubbling and capturing

          本文链接:https://www.haomeiwen.com/subject/uuopsftx.html