Home  >  Article  >  Web Front-end  >  JavaScript blocking event bubbling code compatible with major browsers_javascript skills

JavaScript blocking event bubbling code compatible with major browsers_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:50:52994browse

This is just a simple code demo. Due to time issues, I did not do in-depth research. Because when I was working on the project today, I needed to use content that prevents events from bubbling. I searched a lot before I found one that could be used. I will record it here.

<!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>

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn