博客
关于我
事件冒泡、捕获?如何阻止
阅读量: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 + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
nginx - thinkphp 如何实现url的rewrite
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
Nginx - 反向代理与负载均衡
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx 301跳转
查看>>
nginx 403 forbidden
查看>>
nginx connect 模块安装以及配置
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
nginx http配置说明,逐渐完善。
查看>>
Nginx keepalived一主一从高可用,手把手带你一步一步配置!
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
vue中处理过内存泄露处理方法
查看>>
Nginx RTMP 模块使用指南
查看>>