防止事件冒泡

2019-11-16  本文已影响0人  王远清orz
<style>
    #box1{
      width: 300px;
      height: 300px;
      background-color: red;
    }
    #box2{
      width: 200px;
      height: 200px;
      background-color: blue;
    }
    #box3{
      width: 100px;
      height: 100px;
      background-color: yellow;
    }
  </style>
</head>

<body>
  <div id="box1">
    <div id="box2">
      <div id="box3"></div>
    </div>
  </div>
  <script>
    var box1 = document.getElementById('box1');
    var box2 = document.getElementById('box2');
    var box3 = document.getElementById('box3');
    var array = [box1,box2,box3]
    for( var i = 0; i<array.length;i++){
      var box = array[i];
      box.onclick = function (e) {
        console.log(this.id);
        // 阻止冒泡   
        // e.stopPropagation();

        // 非标准模式,老版本IE支持
        // e.cancelBubble = true;

        //处理浏览器兼容
        stopPropagation(e)
      }
    }
  </script>
</body>

上一篇 下一篇

猜你喜欢

热点阅读