在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者它到达了对象层次的最顶层,即document对象(有些浏览器是window) -摘自网络
这里使用简单的一个demo来演示一下js中的冒泡事件
效果图
布局
<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
在最里层添加了阻止代码后效果
我们可以很明显的看到在使用了阻止的对应方法后,事件没有继续往上层走,被拦截在了当前这一层。
总结
阻止事件冒泡的几种方法
第一种: event.stopPropagation();
第二种: return false;
第三种: event.preventDefault();