天天看點

JS事件冒泡(阻止

<!DOCTYPE html>
 <html xmlns="​​​http://www.w3.org/1999/xhtml​​​">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>無标題文檔</title>
 <style type="text/css">
 *{ margin:0; padding:0;}
 </style>
 </head>
 <body>
 <div id="obj1" style=" width:500px; height:500px; background:#000;">
  <div id="obj2" style="width:400px; height:400px; background:red;"></div>
 </div>
 <script type="text/javascript">
  var obj1 = document.getElementById('obj1');
  var obj2 = document.getElementById('obj2');
  obj1.onclick = function(){
   alert('我點選了obj1');
  }
  obj2.onclick = function(e){
   alert('我點選了obj2');
  }
 </script>
 </body>
 </html>

在通常情況下,我們隻希望事件發生在它的目标而并非它的父級元素上,隻需加個stopBubble方法,即可取消事件冒泡,詳見以下代碼:
<!DOCTYPE html>
 <html xmlns="​​​http://www.w3.org/1999/xhtml​​​">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>無标題文檔</title>
 <style type="text/css">
 *{ margin:0; padding:0;}
 </style>
 </head>
 <body>
 <div id="obj1" style=" width:500px; height:500px; background:#000;">
  <div id="obj2" style="width:400px; height:400px; background:red;"></div>
 </div>
 <script type="text/javascript">
  //阻止事件冒泡的通用函數
  function stopBubble(e){
   // 如果傳入了事件對象,那麼就是非ie浏覽器
   if(e&&e.stopPropagation){
    //是以它支援W3C的stopPropagation()方法
    e.stopPropagation();
   }else{
    //否則我們使用ie的方法來取消事件冒泡
    window.event.cancelBubble = true;
   }
  } var obj1 = document.getElementById('obj1');
  var obj2 = document.getElementById('obj2');
  obj1.onclick = function(){
   alert('我點選了obj1');
  }
  obj2.onclick = function(e){
   alert('我點選了obj2');
   stopBubble(e);
  }
 </script>
 </body>
 </html>