阻止事件冒泡

 

 

复制代码
<body onclick="alert('body')">
    <!--html-->
    <div
      style="width: 400px; height: 400px; background: red"
      onclick="alert(this.style.background)"
    >
      <div
        id="div2"
        style="width: 300px; height: 300px; background: palevioletred"
      >
        <div
          style="width: 200px; height: 200px; background: yellow"
          onclick="alert(this.style.background)"
        >
          <div
            id="div1"
            style="width: 100px; height: 100px; background: palegreen"
          >
            <a id="aaa" href="http://www.baidu.com">aaa</a>
          </div>
        </div>
      </div>
    </div>

    <script>
      //此jquery既阻止默认行为又停止冒泡
      // $("#div1").on('click',function(){
      //     return false;
      // });

      window.onload = function () {
        var oDiv1 = document.getElementById("div1");
        var oDiv2 = document.getElementById("div2");

        oDiv1.onclick = function (ev) {
          var oEvent = ev || event;
          alert("this is div1");

          //js阻止事件冒泡
          //oEvent.cancelBubble = true;
          //oEvent.stopPropagation();

          //js阻止链接默认行为,没有停止冒泡
          //oEvent.preventDefault();
          //return false;
        };

        oDiv2.onclick = function (ev) {
          var oEvent = ev || event;
          alert("this is div2");
          oEvent.cancelBubble = true;
        };
      };
    </script>
复制代码

 

posted @   罗砂  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示