事件冒泡機制
事件冒泡發生的條件:當為多個嵌套的元素設置了相同的事件處理程序,它們將觸發事件冒泡機制。在事件冒泡中,最內部的元素將首先觸發其事件,然后是棧內的下一個元素觸發該事件,以此類推,直到到達最外面的元素。如果把事件處理程序指定給所有的元素,那么這些事件將依次觸發。
舉個例子:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件冒泡</title> <script src="demo2.js"></script> </head> <body> <div id = "first" style="padding : 20px;background-color: #ff0;width: 150px;"> <div id="second" style="background-color :#f00;width:100px;height:100px;border :1px dashed #000"></div> </div> </body> </html>
//demo2.js window.onload = setupEvents; function setupEvents(){ document.getElementById("first").onmousedown=function(){ alert("first element event"); } document.getElementById("second").onmousedown=function(){ alert("second element event"); } document.onmousedown=function(){ alert("document event"); } }
如果單擊最里面的div元素,不論在什么瀏覽器中將彈出三個警告窗口,依次顯示:
1.Second element event
2.First element event
3.Document event

取消事件冒泡機制
如果你有一個元素堆棧,且只希望一個元素觸發該事件處理程序,可以取消事件冒泡機制。IE中的屬性:cancelBubble,Mozila中的屬性:stopPropagation。代碼如下:
function stopEvent(evnt){ if(evnt.stopPropagation){ evnt.stopPropagation(); }else{ evnt.cancelBubble = ture; } }
現在修改demo2.js中的first id的js代碼:
//demo2.js window.onload = setupEvents; function setupEvents(){ // document.getElementById("first").onmousedown=function(){ // alert("first element event"); // } // document.getElementById("first").onmousedown=function(evnt){ var theEvent = evnt ? evnt :window.event; alert("first element event"); stopEvent(theEvent); } document.getElementById("second").onmousedown=function(){ alert("second element event"); } document.onmousedown=function(){ alert("document event"); } } function stopEvent(evnt){ if(evnt.stopPropagation){ evnt.stopPropagation(); }else{ evnt.cancelBubble = ture; } }
然后試驗,你會發現最后一個針對文檔事件處理程序的警告窗口將不會影響,因為在時間到達棧頂之前,事件已經取消了。
