JS如何阻止事件冒泡和如何阻止默认行为

阻止冒泡但不阻止默认行为

e.cancelBubble = true; 
e.stopPropagation();

阻止默认行为但没阻止冒泡

e.preventDefault();
return false;
<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #divOne {
      width: 200px;
      height: 200px;
      border: 1px solid red;
    }
 
    #divTwo {
      width: 100px;
      height: 100px;
      border: 1px solid #666;
    }
  </style>
</head>
 
<body>
  <div>
    <div id="divOne" οnclick="alert('我是最外层');">
      <div id="divTwo" οnclick="alert('我是中间层!')">
        <a id="hr_three" href="http://www.baidu.com" mce_href="http://www.baidu.com">点击我</a>
      </div>
    </div>
  </div>
  <script>
    window.onload = () => {
      document.getElementById("hr_three").onclick = (e) => {
        e = e || window.event;
        /* 
          stopPropagation和cancelBubble阻止事件冒泡,写在事件源最小儿子里面,
          但不会阻击默认行为(它就执行了超链接的跳转)
          弹出“我是最里层” 然后跳转百度 
        */
        // e.stopPropagation() 
        // e.cancelBubble = true; 
        /* 
          e.preventDefault() 
          它的作用是:事件处理过程中,不阻击事件冒泡,但阻击默认行为(它只执行所有弹框,却没有执行超链接跳转)
          依次弹出:我是最里层---->我是中间层---->我是最外层,但最后却没有跳转到百度
        */
        // e.preventDefault()
        /* 
          return false;
          阻止默认行为 但没有阻止冒泡
          依次弹出:我是中间层---->我是最外层,但最后却没有跳转到百度
        */
        return false;
        alert('我是最里层!')
 
      }
    }
  </script>
</body>
 
</html>

猜你喜欢

转载自blog.csdn.net/weixin_45959504/article/details/105627170