HTML結構
HTML DOM elements是嵌套(nested)的結構,如下:
1 2 3 4 5
| <div onclick="alert('點擊最外層');">First // 最外層 <div onclick="alert('點擊第二層');">Second <div onclick="alert('點擊最內層');">Third</div> // 最內層 </div> </div>
|
Event Bubbling
使用JavaScript可以對HTML DOM element
註冊(register)一些不同的event handlers,Event bubbling
是HTML DOM API中事件傳播(event propagation
)的一種方式。
- Bubbling事件傳播的方式為:從事件發生的地方開始一層一層的向最外層傳遞
下面的例子(可以用滑鼠點點看):
1 2 3 4 5 6 7 8 9 10 11
| <div onclick="alert('點擊最外層');" style="background: red; border: 3px dotted black; text-align: center; width: 400px;"> 最外層 <br /> <div onclick="alert('點擊第二層');" style="background: green; border: 4px dotted black; text-align: center; width:300px;"> 第二層 <br /> <div onclick="alert('點擊最內層');" style="background: blue; border: 5px dotted black; text-align: center; width: 250px;"> <font color="white">最內層</font> </div> </div> </div>
|
當你點下(也就是觸發onclick事件)最裡面藍色的那一層的時候,會彈出點擊最內層
的字串,然後再彈出點擊第二層
的字串,最後再彈出點擊最外層
的字串。這就是Bubbling事件傳播
停止Event Bubbling
有時候會想要停止bubbling傳遞事件,可以透過以下的方式來停止,
event.stopPropagation();
event.cancelBubble = true; // IE<9
例如下面的例子(可以用滑鼠點點看):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <script> function disableBubbling(){ alert('點擊了' + event.srcElement.className); event.stopPropagation(); } </script> <div class="最外層" onclick="disableBubbling();" style="background: red; border: 3px dotted black; text-align: center; width: 400px;"> 最外層<br /> <div class="第二層" onclick="disableBubbling();" style="background: green; border: 4px dotted black; text-align: center; width: 300px;"> 第二層<br /> <div class="最內層" onclick="disableBubbling();" style="background: blue; border: 5px dotted black; text-align: center; width: 250px;"> <font color="white">最內層</font> </div> </div> </div>
|