dom事件流分为三个阶段,分别为:
捕获阶段:事件从document节点自上而下向目标节点传播的阶段;
目标阶段:真正的目标节点正在处理事件的阶段;
冒泡阶段:事件从目标节点自上而下向document节点传播的阶段。
捕获阶段:
<!doctype html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>document</title> <style> .father { overflow: hidden; width: 300px; height: 300px; margin: 100px auto; background-color: pink; text-align: center; } .son { width: 200px; height: 200px; margin: 50px; background-color: purple; line-height: 200px; color: #fff; } </style></head><body> <div> <div>son盒子</div> </div> <script> var son = document.queryselector('.son'); son.addeventlistener('click', function() { console.log('son'); }, true); var father = document.queryselector('.father'); father.addeventlistener('click', function() { console.log('father'); }, true); document.addeventlistener('click', function() { console.log('document'); }, true); </script></body></html>
控制台输出结果为:
可以看出捕获阶段 事件是从document节点自上而下向目标节点传播的。
冒泡阶段:
<script> var son = document.queryselector('.son'); son.addeventlistener('click', function() { console.log('son'); }, false); var father = document.queryselector('.father'); father.addeventlistener('click', function() { console.log('father'); }, false); document.addeventlistener('click', function() { console.log('document'); }) </script>
控制台输出结果为:
可以看出冒泡阶段 事件是从目标节点自上而下向document节点传播的。
注意:
1、js代码只能执行捕获或者冒泡其中一个阶段(要么是捕获要么是冒泡)
2、onclick和attachevent(ie)只能得到冒泡阶段
3、addeventlistener(type, listener[, usecapture]) 第三个参数如果是true,表示在事件捕获阶段调用事件处理程序;如果是false(不写默认是false),表示在事件冒泡阶段调用事件处理程序
4、实际开发中,我们很少使用事件捕获,我们更关注事件冒泡
5、有些事件是没有冒泡的,比如onblur、onfocus、onmouseenter、onmouseleave
6、事件的冒泡有时会带来麻烦,不过是可以被阻止的,方法是:stoppropagation()
stoppropagation() 方法:终止事件在传播过程的捕获、目标处理或冒泡阶段进一步传播。调用该方法后,该节点上处理该事件的处理程序将被调用,事件不再被分派到其他节点。
本文来自 js教程 栏目,欢迎学习!
以上就是详解dom事件流的三个阶段的详细内容。