Js事件處理模型/周期

來源:互聯網
上載者:User

標籤:com   function   listener   point   position   尋找   操作   技術分享   事件   

 

  有3個階段

1、  捕獲階段:由外向內,記錄各級父元素上綁定的事件處理函數---只記錄,不觸發。

2、  目標觸發:優先觸發目標元素上的事件處理函數。

3、  冒泡:由內向外,按捕獲的順序的相反的方向,依次執行父元素上的事件處理函數。

 過程如所示:

如果希望阻止某些冒泡行為,如表單驗證失敗時,不允許提交,可以使用e.stopPropagation();取消冒泡: 

什麼時候使用利用冒泡:

都知道,瀏覽器通過遍曆方式尋找事件處理函數執行。如果添加的事件監聽越多,遍曆越慢,網頁響應速度越慢,因此

盡量少的添加事件監聽.

如果多個平級子項目綁定相同事件時,可在父元素僅添加一個事件監聽,所有子項目共用,並且使用e.target擷取目標元素.

 

下面的代碼是一個很經典的理解事件處理的例子:

這裡,咱希望的是,點擊那個div,那個就變黃,可是如果不加e.stopPropagation的話,在點擊d3或d2時,都會冒泡執行其父元素的操作,

比如點擊,最裡面的d3,上面的d2,d1都會依次變黃.

<!DOCTYPE HTML><html>    <head>        <title>事件處理</title>        <meta charset="utf-8"/>         <style>            .d1 .d2 .d3{cursor:pointer}            .d1 {              background-color: green;              position: relative;              width: 150px;              height: 150px;              text-align: center;              cursor: pointer;            }            .d2 {              background-color: blue;              position: absolute;              top: 25px;              left: 25px;              width: 100px;              height: 100px;            }            .d3 {              background-color: red;              position: absolute;              top: 25px;              left: 25px;              width: 50px;              height: 50px;              line-height: 50px;            }                  </style>            </head>    <body>        <div class="d1">            <div class="d2">                <div class="d3">                </div>            </div>        </div>    <script>            function highLight(e){        this.style.background="yellow";        alert(this.className);        this.style.background="";        //取消冒泡  如果不加的話,在點擊d3或d2時,都會冒泡執行其父元素的操作        e.stopPropagation();      }            document.querySelector(".d1")        .addEventListener(          "click",highLight);      document.querySelector(".d2")        .addEventListener(          "click",highLight);      document.querySelector(".d3")        .addEventListener(          "click",highLight);        </script>    </body></html>

 

Js事件處理模型/周期

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.