一個事件冒泡的例子:javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function () { $('body').click(function () { alert(4); }); $('.grandfather').click(function () { alert(3); }); $('.father').click(function () { alert(2); }); $('.son').click(function () { alert(1); }); }) </script> <style type="text/css"> .grandfather{ width:300px; height:300px; background-color: gold; position: relative; } .father{ width:200px; height:200px; background-color: hotpink; } .son{ width:100px; height:100px; background-color: chartreuse; position: absolute; left:0; top:400px; } </style> </head> <body> <div class="grandfather"> <div class="father"> <div class="son"></div> </div> </div> </body> </html>
事件冒泡有時候是不須要的,須要阻止掉,經過event.stopPropagation()來阻止css
$('body').click(function (event) { alert(4); event.stopPROpagation(); });
阻止默認行爲:(阻止右鍵菜單)html
$(document).contextmenu(function(event){ event.preventDefault(); })
合併阻止操做:java
實際開發中通常把阻止冒泡和阻止默認行爲合併起來寫jquery
return false;ide
eg:(彈框--阻止冒泡)性能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function () { $('#btn').click(function () { $('#pop').show(); return false; }); $('#shutoff').click(function () { $('#pop').hide(); }); $(document).click(function (event) { $('#pop').hide(); }); $('.pop').click(function () { return false; }) }) </script> <style type="text/css"> .pop_con{ /*暫時隱藏*/ display: none; } .pop{ width: 300px; height:200px; background-color: #fff; border:1px solid #000; /*使框居中*/ position: fixed; left:50%; top:50%; margin-left:-150px; margin-top: -100px; /*讓彈窗覆蓋在mask上面*/ z-index:9999; } .mask{ position: fixed; width:100%; height: 100%; background-color: #000; left:0; top:0; /*設置透明度*/ opacity:0.3; /*ie兼容的透明度*/ filter:alpha(opacity=0.3); /*讓彈窗覆蓋在mask上面*/ z-index:9990; } </style> </head> <body> <h1>首頁標題</h1> <p>頁面內容</p> <input type="button" name="" value="彈出" id="btn"> <!--自制彈框--> <div class="pop_con" id="pop"> <div class="pop"> <h3>提示信息!</h3> <a href="#" id="shutoff">關閉</a> <input type="text" name=""> </div> <div class="mask">mask</div> </div> </body> </html>
事件委託:利用事件冒泡原理把事件加到父級上,經過判斷事件來源的子集,執行相應的操做,事件委託首先能夠極大減小事件綁定次數,提升性能;其次可讓新加入的子元素也擁有相同的操做。this
<script type="text/javascript"> <!--事件委託寫法--> $(function () { $('.list').delegate('li','click',function () { alert($(this).html());
//取消委託
$('.list').undelegate();
}); }) </script>