JS事件冒泡(阻止)

来源:互联网 发布:淘宝店铺不支持7天退货 编辑:程序博客网 时间:2024/06/06 16:53

来源:http://blog.csdn.net/tnjun123456/article/details/7105935

在默认情况下,发生在一个子元素上的单击事件(或者其他事件),如果在其父级元素绑定了一个同样的事件,此时点击子元素,click事件会首先被子元素捕获,执行绑定的事件程序,之后会被父级元素捕获,再次激发一段脚本的执行,这就是所谓的“事件冒泡”。

看个例子:

[html] view plaincopy
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>无标题文档</title>  
  6. <style type="text/css">  
  7. *{ margin:0; padding:0;}  
  8. </style>  
  9. </head>  
  10. <body>  
  11. <div id="obj1" style=" width:500px; height:500px; background:#000;">  
  12.     <div id="obj2" style="width:400px; height:400px; background:red;"></div>  
  13. </div>  
  14. <script type="text/javascript">  
  15.     var obj1 = document.getElementById('obj1');  
  16.     var obj2 = document.getElementById('obj2');  
  17.     obj1.onclick = function(){  
  18.         alert('我点击了obj1');  
  19.     }  
  20.     obj2.onclick = function(e){  
  21.         alert('我点击了obj2');  
  22.     }  
  23. </script>  
  24. </body>  
  25. </html>  


在通常情况下,我们只希望事件发生在它的目标而并非它的父级元素上,只需加个stopBubble方法,即可取消事件冒泡,详见以下代码:

[html] view plaincopy
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>无标题文档</title>  
  6. <style type="text/css">  
  7. *{ margin:0; padding:0;}  
  8. </style>  
  9. </head>  
  10. <body>  
  11. <div id="obj1" style=" width:500px; height:500px; background:#000;">  
  12.     <div id="obj2" style="width:400px; height:400px; background:red;"></div>  
  13. </div>  
  14. <script type="text/javascript">  
  15.     //阻止事件冒泡的通用函数  
  16.     function stopBubble(e){  
  17.         // 如果传入了事件对象,那么就是非ie浏览器  
  18.         if(e&&e.stopPropagation){  
  19.             //因此它支持W3C的stopPropagation()方法  
  20.             e.stopPropagation();  
  21.         }else{  
  22.             //否则我们使用ie的方法来取消事件冒泡  
  23.             window.event.cancelBubble = true;  
  24.         }  
  25.     }  
  26.   
  27.     var obj1 = document.getElementById('obj1');  
  28.     var obj2 = document.getElementById('obj2');  
  29.     obj1.onclick = function(){  
  30.         alert('我点击了obj1');  
  31.     }  
  32.     obj2.onclick = function(e){  
  33.         alert('我点击了obj2');  
  34.         stopBubble(e);  
  35.     }  
  36. </script>  
  37. </body>  
  38. </html>  

现在你可能想知道,什么时候需要阻止事件冒泡?事实上,现在绝大多数情况下都可以不必在意它。但是当你开始开发动态应用程序(尤其是需要处理键盘和鼠标)的时候,就有这个必要了。


0 0
原创粉丝点击