標籤: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事件處理模型/周期