码迷,mamicode.com
首页 > 其他好文 > 详细

捕获、冒泡

时间:2019-03-05 09:17:41      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:listen   href   开始   dev   处理   lan   utf-8   tle   charset   

参考资料

一个DOM元素绑定多个事件时,先执行冒泡还是捕获
https://www.cnblogs.com/greatluoluo/p/5882508.html

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

从上往下,如有捕获事件,则执行;一直向下到目标元素后,从目标元素开始向上执行冒泡元素,即第三个参数为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

捕获、冒泡

标签:listen   href   开始   dev   处理   lan   utf-8   tle   charset   

原文地址:https://www.cnblogs.com/gleamer/p/10474415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!