兼容各大浏览器的JavaScript阻止事件冒泡代码

作者:白露

时间:2026-10-29

浏览:379

本文分享一段用于阻止JavaScript事件冒泡的简单代码示例。针对项目中遇到的跨浏览器兼容性问题,通过封装stopEvent函数实现冒泡阻止,并附带完整的HTML与JS结构供参考。

文章目录

阻止事件冒泡的代码实现

本文仅展示一个基础代码示例。由于时间有限,未进行深度研究。在近期项目开发中,因需要实现阻止事件冒泡的功能,经过多次搜索后找到了一个可用的方案,特此记录。


<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>阻止事件冒泡</title>
  <script src="js/jquery-1.11.3.min.js"></script>
  <script src="js/jquery.cookie.js"></script>
  <style type="text/css">
  </style>
  <script type="text/javascript">
    function clickDiv(){
      alert("clickDiv");
    }
    function clickP(event){
      stopEvent(event);
      alert("clickP");
    }
    function stopEvent(event){ //阻止冒泡事件
     //取消事件冒泡
     var e=arguments.callee.caller.arguments[0]||event; //若省略此句,下面的e改为event,IE运行可以,但是其他浏览器就不兼容
     if (e && e.stopPropagation) {
     // this code is for Mozilla and Opera
     e.stopPropagation();
     } else if (window.event) {
     // this code is for IE
      window.event.cancelBubble = true;
     }
    }
  </script>
</head>
<body>
  <div onclick="clickDiv()" style="width:100px; height:100px; background-color:red;">
    <p onclick="clickP(event)" style="width:50px; height:50px; margin:auto; background-color:green;">
      abad
    </p>
  </div>
  <script type="text/javascript">
  </script>
</body>
</html>

以上内容为本文的全部介绍,希望读者能够喜欢。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章