JS-JQ-事件冒泡

一、冒泡的原理:

  子元素会触发父元素的事件

  自上而下的触发事件

二、解决方法:

  JS:

     IE:event.cancelBubble=true  

     FF:event.stopPropagation()

  JQ:

      ev.stopPropagation()

!!! - CSS

<style>
  .div1{800px;height:500px;padding:100px;box-sizing: border-box;background:rosybrown;}
  .div2{500px;height:200px;background:#269ABC;}
</style>

!!! - HTML

<div class="div1">
  <div class="div2"></div>
</div>

!!! - JavaScript

window.onload=function()
{
  var div1=document.getElementsByClassName('div1')[0];
  var div2=document.getElementsByClassName('div2')[0];
  div1.onclick=function()
  {
    alert('我是DIV1');
  }
  div2.onclick=function(ev)
  {
    var oEvent=ev||event;
    if(ev.cancelBubble)
    {
      oEvent.cancelBubble=true;
    }
    else
    {
      oEvent.stopPropagation();
    }
    alert('我是DIV2');
  }
}

!!! - JQuery

$(function(){
  $('.div1').click(function(){
    alert('我是DIV1');
  });
  $('.div2').click(function(ev){
    alert('我是DIV2');
    ev.stopPropagation();
  });
})

原文地址:https://www.cnblogs.com/xiaoyangtian/p/7922118.html