博客
关于我
事件冒泡、捕获?如何阻止
阅读量:388 次
发布时间:2019-03-05

本文共 1689 字,大约阅读时间需要 5 分钟。

事件冒泡

    
content
wraper
box

在这里插入图片描述

点击box后触发了wraper,content绑定的点击事件。这种由子元素向祖先元素触发的事件处理模型叫做事件冒泡。

事件冒泡应用:事件委托

利用事件冒泡,和事件源对象(e[非IE事件对象].target或event[IE事件对象].srcElement)进行处理。

事件捕获

事件捕获只需要把监听事件的第三个参数,false改为true。

box.addEventListener('click',function(e){           console.log('box')    },true)    wraper.addEventListener('click',function(e){           console.log('wraper')    },true)    content.addEventListener('click',function(e){           console.log('content')    },true)

在这里插入图片描述

发现控制台打印结果,反了过来,从祖先元素往子元素依次触发事件。IE不存在事件捕获。

事件冒泡和捕获优先级

// 事件捕获    box.addEventListener('click',function(e){           console.log('box捕获')    },true)    wraper.addEventListener('click',function(e){           console.log('wraper捕获')    },true)    content.addEventListener('click',function(e){           console.log('content捕获')    },true)    // 事件冒泡    box.addEventListener('click',function(e){           console.log('box冒泡')    },false)    wraper.addEventListener('click',function(e){           console.log('wraper冒泡')    },false)    content.addEventListener('click',function(e){           console.log('content冒泡')    },false)

在这里插入图片描述

由结果可知,先执行事件捕获,在执行事件冒泡。

阻止事件捕获,冒泡

使用e.stopPropagation()

IE使用event.cancelBubble = true(兼容所有IE) 或 event.stopPropagation() (IE9以下不兼容)

box.addEventListener('click',function(e){           e.stopPropagation()        console.log('box冒泡')    },false)    wraper.addEventListener('click',function(e){           console.log('wraper冒泡')    },false)    content.addEventListener('click',function(e){           console.log('content冒泡')    },false)

在这里插入图片描述

阻止事件捕获和事件冒泡都可以使用这个事件对象的stopPropagation方法阻止。

转载地址:http://nkhwz.baihongyu.com/

你可能感兴趣的文章
Nginx学习总结(14)——Nginx配置参数详细说明与整理
查看>>
Nginx安装与常见命令
查看>>
Nginx安装及配置详解
查看>>
Nginx实战经验分享:从小白到专家的成长历程!
查看>>
Nginx实现反向代理负载均衡
查看>>
nginx实现负载均衡
查看>>
nginx开机启动脚本
查看>>
nginx异常:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf
查看>>
nginx总结及使用Docker创建nginx教程
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
查看>>
nginx日志分割并定期删除
查看>>
Nginx日志分析系统---ElasticStack(ELK)工作笔记001
查看>>
Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
查看>>
nginx最最最详细教程来了
查看>>
Nginx服务器---正向代理
查看>>
Nginx服务器上安装SSL证书
查看>>
Nginx服务器的安装
查看>>
Nginx模块 ngx_http_limit_conn_module 限制连接数
查看>>
nginx添加模块与https支持
查看>>