事件冒泡
<style>
div{
color: white;
font-size: 30px;
}
.content{
width: 400px;
height: 400px;
background-color: blue;
position: relative;
}
.wraper{
width: 300px;
height: 300px;
background-color:yellowgreen;
position: absolute;
left: 400px;
}
.box{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 300px;
}
</style>
</head>
<body>
<div class="content">
content
<div class="wraper">
wraper
<div class="box">
box
</div>
</div>
</div>
</body>
<script>
var box = document.getElementsByClassName("box")[0]
var wraper = document.getElementsByClassName("wraper")[0]
var content = document.getElementsByClassName("content")[0]
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)
</script>
点击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方法阻止。