JS的冒泡事件


 

在一個對象上觸發某類事件(比如單擊onclick事件),如果此對象定義了此事件的處理程序,那么此事件就會調用這個處理程序,如果沒有定義此事件處理程序或者事件返回true,那么這個事件會向這個對象的父級對象傳播,從里到外,直至它被處理(父級對象所有同類事件都將被激活),或者它到達了對象層次的最頂層,即document對象(有些瀏覽器是window) -摘自網絡

這里使用簡單的一個demo來演示一下js中的冒泡事件

效果圖

http://of4osh4j5.bkt.clouddn.com/propanation_js.gif

布局

<div class="first_div"> 最外層div <div class="second_div"> 中間層 <div class="third_div"> 最里層 </div> </div> </div> <div class="msg_div"></div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

也就是三個DIV分別為不同的背景色

CSS

    <style type="text/css"> div { border: solid 1px deepskyblue; padding: 2em; width: 30% } div .third_div { background-color: red; } div .second_div { background-color: deepskyblue; } .first_div { height: auto; background-color: lawngreen; } </style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

jquery添加事件並且在點擊后有對應文本輸出顯示

<!--javascript代碼-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" language="JavaScript"> // alert(parseInt(Math.floor(Math.random() * 10))); $(function () { $('.third_div').bind('click', function (event) { func("你點擊最里層DIV") // event.stopPropagation(); // return false; }); $('.second_div').bind('click', function (event) { func("你點擊了中間層DIV") // event.stopPropagation(); // return false; }); $('.first_div').bind('click', function (event) { func("你點擊了最外層DIV") // event.stopPropagation(); // return false; }); $('body').bind('click', function () { func("你點擊了body"); // event.stopPropagation(); // return false; }) }) var colorArray = new Array("blue", "grey", "green", "red", "orangered", "darkviolet", "orange", "crimson", "chartreuse", "black"); var count = 0; var func = function (str) { count++; var child = $("<div></div>"); child.css({ "color": colorArray[parseInt(Math.floor(Math.random() * 10))], "border": "solid 1px grey", "padding": "0.5em" }); child.text(count + ":" + str); $('.msg_div').append(child); if (count % 3 === 0) { count = 0; $('.msg_div div:last-child').after("<hr>"); } }; </script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

在最里層添加了阻止代碼后效果

我們可以很明顯的看到在使用了阻止的對應方法后,事件沒有繼續往上層走,被攔截在了當前這一層。

http://of4osh4j5.bkt.clouddn.com/propanation_js_stop.gif

總結

阻止事件冒泡的幾種方法


第一種: event.stopPropagation(); 
第二種: return false; 
第三種: event.preventDefault(); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM