阻止冒泡和浏览器默认行为

冒泡

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
  .box1{
    height: 500px;
    width:500px;
    background:red;
  }
  .box2{
    height: 300px;
    width:300px;
    background:green;
  }
  .box3{
    height: 100px;
    width:100px;
    background:blue;
  }
  </style>
</head>
<body>
  <div class="box1">
    <div class="box2">
      <div class="box3">

      </div>
    </div>
  </div>
</body>
<script type="text/javascript">
window.onload = function(){
  var box1 = document.getElementsByClassName('box1')[0]
  var box2 = document.getElementsByClassName('box2')[0]
  var box3 = document.getElementsByClassName('box3')[0]
  box1.onclick = function(e){
    console.log('单击了红色的');
  }
  box2.onclick= function(){
    console.log('单击了绿色');
  }
  box3.onclick=function(e){
//如果提供了事件对象,则这是一个非IE浏览器
  if(e&e.stopPropagation)  
//W3C的方法
  e.stopPropagation();  
  else
//这是IE的方式
  window.event.cancelBubble = true;
    console.log('单击了蓝色的');
  }
}

</script>
</html>

上述例子 最里面的蓝色块已经被阻止了冒泡,绿色块是有冒泡的。

//阻止浏览器默认行为
function stopDefault(e){
//阻止默认浏览器动作(W3C)
if(e&&e.preventDefault)
e.preventDefault();
//IE中阻止浏览器默认动作的方式
else
window.event.trturnValue = false;
return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值