码迷,mamicode.com
首页 > Web开发 > 详细

js事件冒泡、事件捕获

时间:2019-01-15 20:33:38      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:body   image   var   sele   code   写法   冒泡   cli   事件触发   

事件冒泡

技术分享图片

        var box = document.querySelector('.box');
    var content = document.querySelector('.content');
    document.addEventListener('click', function(e) {
      console.log('document');
    }, false);
    document.body.addEventListener('click', function(e) {
      console.log('body');
    }, false);
    box.addEventListener('click', function(e) {
      console.log('box');
    }, false);
    content.addEventListener('click', function(e) {
      console.log('content');
    }, false);
        

当我们点击.content时,事件的执行顺序是content - box - body - document。所以事件冒泡的走向是由子节点向父节点去触发同名事件

技术分享图片

事件捕获

技术分享图片

        var box = document.querySelector('.box');
    var content = document.querySelector('.content');
    document.addEventListener('click', function(e) {
      console.log('document');
    }, true);
    document.body.addEventListener('click', function(e) {
      console.log('body');
    }, true);
    box.addEventListener('click', function(e) {
      console.log('box');
    }, true);
    content.addEventListener('click', function(e) {
      console.log('content');
    }, true);
        

当我们点击.content时,事件的执行顺序是document - body - box - content。所以事件冒泡的走向是由父节点向子节点去触发同名事件

技术分享图片

总结:

addEventListener('', function(e) {}, false);

第三个参数可控制事件是冒泡还是捕获,js逻辑写法的先后顺序与事件触发的顺序无关

js事件冒泡、事件捕获

标签:body   image   var   sele   code   写法   冒泡   cli   事件触发   

原文地址:https://www.cnblogs.com/frogblog/p/10274035.html

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