JS事件冒泡、停止冒泡、addEventListener--執行個體示範

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   java   strong   ar   

問題:

 <div class=‘item‘ id=‘outer‘ onclick="alert(‘outer‘)">    <div class=‘item‘ id=‘inner‘ onclick="alert(‘inner‘);">      <div class=‘item‘ id=‘core‘ onclick="alert(‘core‘)">         core!!!!!      </div>    </div>  </div>

1.上面div中,如果單擊core,會執行多少個alert?先後順序是上面?

   冒泡就是處理DOM節點樹中,各個節點綁定事件執行流程的一種方式;

   因為各瀏覽器軟體和相關組織間的差異,事件流有三種:事件冒泡、事件捕獲、DOM事件流,其中DOM事件流已被所有主要瀏覽器實現;

2.chorme用的是冒泡事件流方式,這個例子解釋了冒泡事件流的事件執行順序;

3.  stopPropagation()是停止冒泡事件流。如果你在node A節點添加該方法,那麼“泡泡“就在node A這個位置破了,其後的所有節點綁定事件都不執行;

3.同時使用了addEventListener,向某節點添加事件;

4.下面是代碼,儲存成html檔案,看看效果;

<html><head>  <style type="text/css">     .item{         display: table;         margin: 100px;     }     #outer{         width:400px;         height:400px;         background-color: blue;              }      #inner{         vertical-align: middle;         width:200px;         height:200px;         background-color: white;              }     #core{         width:80px;         height:80px;         background-color: red;         text-indent: 10px;         line-height: 50px;              }  </style>  </head><body>  <div class=‘item‘ id=‘outer‘ onclick="alert(‘outer‘)">    <div class=‘item‘ id=‘inner‘ onclick="alert(‘inner‘);stopbubble(arguments[0])">      <div class=‘item‘ id=‘core‘ onclick="alert(‘core‘)">         core!!!!!      </div>    </div>  </div></body><!--you must write <script> under <body>--><script type=‘text/javascript‘>          var core = document.getElementById(‘core‘);        core.addEventListener("click",function(){alert(‘dddddd‘)},false);        //addEventListener: can add one more event to node "core"             function stopbubble(e){              e.stopPropagation();//stop bubble event on this node         }</script></html>

 

前端效果:

 

點擊core!!!後:
1.先alert core 因為綁定了dddd,然後會alert  dddd;

2.然後冒泡到inner節點後,alert inner,但是同時執行stopbubble(arguments[0])來停止冒泡;

3.停止冒泡後,該node後續節點就不執行了,所以不會alert outer;

JS事件冒泡、停止冒泡、addEventListener--執行個體示範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.