JavaScript 捕获、冒泡

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

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    #one {
      width: 300px;
      height: 300px;
      background-color: red;
    }

    #two {
      width: 200px;
      height: 200px;
      background-color: green;
    }

    #three {
      width: 100px;
      height: 100px;
      background-color: blue;
    }
	#four {
      width: 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

参考资料

  1. 一个DOM元素绑定多个事件时,先执行冒泡还是捕获 - 张三的美丽家园 - 博客园 https://www.cnblogs.com/greatluoluo/p/5882508.html

  2. EventTarget.addEventListener() - Web API 接口参考 | MDN
    https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener

posted @ 2019-03-05 02:14  gleamer  阅读(199)  评论(0编辑  收藏  举报