JS阻止事件冒泡

来源:互联网 发布:linux在根目录下新建 编辑:程序博客网 时间:2024/05/18 21:42

JS事件流中有一种事件被称为“冒泡事件”,当一个元素被触发一个事件时,该目标元素上的事件会优先被执行,然后向外传播到每个祖先元素,恰如水里的一个泡泡似的,从产生就一直往上冒,到达水平面时,它才消失。在这个过程中,如果你只希望触发目标元素上的事件,而不想它传播到祖先元素上去,那么你需要在“泡泡”离开对象之前刺破它。下面,就以一个简单的Demo来演示下JS如何阻止事件冒泡:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">      <html>      <head>      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      <title>js阻止事件冒泡的DEMO</title>      <script type="text/javascript">          //阻止冒泡的方法          function stopPP(e)          {              var eevt = e || window.event;              //IE用cancelBubble=true来阻止而FF下需要用stopPropagation方法              evt.stopPropagation ? evt.stopPropagation() : (evt.cancelBubble=true);          }      </script>      </head>      <body>      <div style="margin: 150px 400px;width: 700px; height: 550px; background-color: #878788;" onclick="alert('最外层div上的onclick事件');">      <h2>最外层div上的onclick事件</h2>      <div style="margin: 100px; width: 500px; height: 300px; background-color: #545444;" onclick="stopPP(arguments[0]);alert('中间层div上的onclick事件');">      <h3>中间层div上的onclick事件</h3>      <div style="margin: 60px 100px; height: 100px; width: 300px; background-color: red;" onclick="stopPP(arguments[0]);alert('最内层div上的onclick事件');">      <h4>最内层div上的onclick事件”</h4>      </div>      </div>      </div>             </body>      </html>   



原创粉丝点击