JavaScript 设置事件流流向

多层标签嵌套如果绑定了相同的事件,那么触发其中某一个标签的事件后,其关联的其他标签也会同时响应该事件,如下图所示:

002C1816-141C-483F-B37A-3AEABFA6D04C

图中 div 嵌套 pp 又嵌套了一个 span。并且标注了每个标签元素都绑定了 onclick 事件,当点击 span 标签时其上层的两个标签元素也都会响应,但响应的过程分为冒泡型和捕捉型。当添加事件时指定事件的第三个参数为 true 时,该元素的事件就变为捕捉型(由外向内),如果第三个参数指定为 false(默认值)时,该元素的事件就变为冒泡型。

捕捉型参考代码及效果

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <title>js lesson</title>
    <style>
      div {
        width: 400px;
        height: 300px;
        background-color: pink;
      }
      p {
        width: 300px;
        height: 200px;
        background-color: lightsteelblue;
      }
      span {
        font-size: 22px;
        background-color: darkslategray;
        color: #FFF;
      }
    </style>
  </head>
<body>
  <h2>DOM 操作</h2>
  <div>
    <p><span>Today is Sunday</span></p>
  </div>
</body>
</html>
<script type="text/javascript">
  var sp = document.getElementsByTagName("span")[0];
  var pt = document.getElementsByTagName("p")[0];
  var dv = document.getElementsByTagName("div")[0];

  sp.addEventListener("click", function() {
    console.log("This is span tag");
  }, true);
  pt.addEventListener("click", function() {
    console.log("This is p tag");
  }, true);
  dv.addEventListener("click", function() {
    console.log("This is div tag");
  }, true);
</script>

屏幕快照 2015-11-22 下午2.43.05

冒泡型参考代码及效果

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <title>js lesson</title>
    <style>
      div {
        width: 400px;
        height: 300px;
        background-color: pink;
      }
      p {
        width: 300px;
        height: 200px;
        background-color: lightsteelblue;
      }
      span {
        font-size: 22px;
        background-color: darkslategray;
        color: #FFF;
      }
    </style>
  </head>
<body>
  <h2>DOM 操作</h2>
  <div>
    <p><span>Today is Sunday</span></p>
  </div>
</body>
</html>
<script type="text/javascript">
  var sp = document.getElementsByTagName("span")[0];
  var pt = document.getElementsByTagName("p")[0];
  var dv = document.getElementsByTagName("div")[0];

  sp.addEventListener("click", function() {
    console.log("This is span tag");
  }, false);
  pt.addEventListener("click", function() {
    console.log("This is p tag");
  }, false);
  dv.addEventListener("click", function() {
    console.log("This is div tag");
  }, false);
</script>

屏幕快照 2015-11-22 下午2.42.09

1 comment

评论