Js事件处理模型/周期

  有3个阶段

1、  捕获阶段:由外向内,记录各级父元素上绑定的事件处理函数---只记录,不触发。

2、  目标触发:优先触发目标元素上的事件处理函数。

3、  冒泡:由内向外,按捕获的顺序的相反的方向,依次执行父元素上的事件处理函数。

 过程如下图所示:

如果希望阻止某些冒泡行为,如表单验证失败时,不允许提交,可以使用e.stopPropagation();取消冒泡: 

什么时候使用利用冒泡:

都知道,浏览器通过遍历方式查找事件处理函数执行。如果添加的事件监听越多,遍历越慢,网页响应速度越慢,因此

尽量少的添加事件监听.

如果多个平级子元素绑定相同事件时,可在父元素仅添加一个事件监听,所有子元素共用,并且使用e.target获取目标元素.

下面的代码是一个很经典的理解事件处理的例子:

这里,咱希望的是,点击那个div,那个就变黄,可是如果不加e.stopPropagation的话,在点击d3或d2时,都会冒泡执行其父元素的操作,

比如点击,最里面的d3,上面的d2,d1都会依次变黄.

<!DOCTYPE HTML>
<html>
    <head>
        <title>事件处理</title>
        <meta charset="utf-8"/>
         <style>
            .d1 .d2 .d3{cursor:pointer}
            .d1 {
              background-color: green;
              position: relative;
              width: 150px;
              height: 150px;
              text-align: center;
              cursor: pointer;
            }

            .d2 {
              background-color: blue;
              position: absolute;
              top: 25px;
              left: 25px;
              width: 100px;
              height: 100px;
            }

            .d3 {
              background-color: red;
              position: absolute;
              top: 25px;
              left: 25px;
              width: 50px;
              height: 50px;
              line-height: 50px;
            }
         
         </style>
        
    </head>
    <body>
        <div class="d1">
            <div class="d2">
                <div class="d3">
                </div>
            </div>
        </div>
    <script>
            function highLight(e){
        this.style.background="yellow";
        alert(this.className);
        this.style.background="";
        //取消冒泡  如果不加的话,在点击d3或d2时,都会冒泡执行其父元素的操作
        e.stopPropagation();
      }
            document.querySelector(".d1")
        .addEventListener(
          "click",highLight);
      document.querySelector(".d2")
        .addEventListener(
          "click",highLight);
      document.querySelector(".d3")
        .addEventListener(
          "click",highLight);
        </script>
    </body>
</html>
原文地址:https://www.cnblogs.com/web-fusheng/p/6745057.html