zoukankan      html  css  js  c++  java
  • 事件冒泡与事件捕获的作用与区别

    首先了解什么是冒泡事件与捕获事件

    冒泡事件:是指子元素向父元素传递的过程
    捕获事件:是指父元素向子元素传递的过程

    <style> 
      div {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      #box1 {
        height: 150px;
        background-color: red;
       
      }
      #box2 {
         80%;
        height: 100px;
        background-color: yellow;
      }
      #box3 {
         80%;
        height: 50px;
        background-color: green;
      }
    </style>
    <body>
      <div id="box1">
        <div id="box2">
          <div id="box3"></div>
        </div>
      </div>
    </body>
    </html>
    <script  type="text/javascript">
      var box1 = document.getElementById("box1");
      var box2 = document.getElementById("box2");
      var box3 = document.getElementById("box3");
      // addEventListener 事件默认为false,也就是我们所说的事件冒泡过程
      box1.addEventListener('click', function(){
        alert("box1 被触发了");
      })
    
      box2.addEventListener('click', function(){
        alert("box2 被触发了");
      })
    
      box3.addEventListener('click', function(){
        alert("box3 被触发了");
      })
    
      // 点击box3打印结果
      // box3 
      // box2
      // box1
      
      // 当我们将 addEventListener 设置为true时,此时就成了事件捕获的过程
      box1.addEventListener('click', function(){
        alert("box1 被触发了");
      }, true)
    
      box2.addEventListener('click', function(){
        alert("box2 被触发了");
      }, true)
    
      box3.addEventListener('click', function(){
        alert("box3 被触发了");
      })
    
      // 点击box3打印结果
      // box1 
      // box2
      // box3
    
      // 阻止事件冒泡
      box1.addEventListener('click', function(){
        alert("box1 被触发了");
      })
    
      box2.addEventListener('click', function(event){
        alert("box2 被触发了");
        event.stopPropagation();
      })
    
      box3.addEventListener('click', function(){
        alert("box3 被触发了");
      })
    
      // 点击box3打印结果
      // box3
      // box2
      
      // 阻止事件捕获
      box1.addEventListener('click', function(){
        alert("box1 被触发了");
      }, true)
    
      box2.addEventListener('click', function(event){
        alert("box2 被触发了");
        event.stopPropagation();
      }, true)
    
      box3.addEventListener('click', function(){
        alert("box3 被触发了");
      })
    
      // 点击box3打印结果
      // box1
      // box2
    
    </script>

     

  • 相关阅读:
    iptables详解
    Python中的Subprocess模块
    Logging模块
    python inspect.stack() 的简单使用
    python之inspect模块
    python之platform模块
    GlusterFS分布式存储学习笔记
    AD 域服务简介(一)- 基于 LDAP 的 AD 域服务器搭建及其使用
    LDAP概念和原理介绍
    文件传输协议FTP、SFTP和SCP
  • 原文地址:https://www.cnblogs.com/fczbk/p/13607188.html
Copyright © 2011-2022 走看看