zoukankan      html  css  js  c++  java
  • 捕获、冒泡

    参考资料

    一个DOM元素绑定多个事件时,先执行冒泡还是捕获 https://www.cnblogs.com/greatluoluo/p/5882508.html
    https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener

    所有事件的顺序是:其他元素捕获阶段事件 -> 本元素代码顺序事件 -> 其他元素冒泡阶段事件 。
    首先,无论是冒泡事件还是捕获事件,元素都会先执行捕获阶段。

    从上往下,如有捕获事件,则执行;一直向下到目标元素后,从目标元素开始向上执行冒泡元素,即第三个参数为true表示捕获阶段调用事件处理程序,如果是false则是冒泡阶段调用事件处理程序
    (在向上执行过程中,已经执行过的捕获事件不再执行,只执行冒泡事件。)

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Document</title>
      <style>
        #one {
           300px;
          height: 300px;
          background-color: red;
        }
    
        #two {
           200px;
          height: 200px;
          background-color: green;
        }
    
        #three {
           100px;
          height: 100px;
          background-color: blue;
        }
    	#four {
           50px;
          height: 50px;
          background-color: skyblue;
        }
      </style>
    </head>
    <body>
    	<div id='one'>
    	  <div id='two'>
    		<div id='three'>
    		  <div id='four'>
    		  </div>
    		</div>
    	  </div>
    	</div>
    	<script>
    
    	 var one=document.getElementById('one');
    	 var two=document.getElementById('two');
    	 var three=document.getElementById('three');
    	 var four=document.getElementById('four');
    
    
    	one.addEventListener('click',function(){
    	console.log('one');
    	},true);
    	two.addEventListener('click',function(){
    	console.log('two');
    	},false);
    	three.addEventListener('click',function(){
    	console.log('three');
    	},true);
    	four.addEventListener('click',function(){
    	console.log('four');
    	},false);
    	</script> 
    </body>
    </html>
    
    
    

    此时点击four元素,four元素为目标元素,one为根元素祖先,从one开始向下判断执行。

    one为捕获事件,输出one;

    two为冒泡事件,忽略;

    three为捕获时间,输出three;

    four为目标元素,开始向上冒泡执行,输出four;(从此处分为两部分理解较容易。)

    three为捕获已执行,忽略;

    two为冒泡事件,输出two;

    one为捕获已执行,忽略。

    最终执行结果为:

    one
    three
    four
    two

  • 相关阅读:
    [Java算法分析与设计]--链式堆栈的设计
    Spring 单例模式和多例模式
    lucene_09_solrj的使用
    lucene_08_solr导入数据库数据
    lucene_07_solr使用IK分词器
    lucene_06_solr域
    lucene_05_solr配置
    lucene_04_解析语法查询
    lucene_03_索引的增删改查
    lucene_02_IKAnalyre
  • 原文地址:https://www.cnblogs.com/gleamer/p/10474415.html
Copyright © 2011-2022 走看看