事件冒泡:结构上(非视觉上)嵌套关系的元素,会存在事件冒泡的功能,即同一事件,自子元素冒泡向父元素。(自底向上)
css:
#container{
width:300px;
height:300px;
background:red;
}
#father{
width:200px;
height:200px;
background:green;
margin-left:300px;
}
#son{
width:100px;
height:100px;
background:blue;
margin-left:200px;
}
html:
<div id="container">
<div id="father">
<div id="son"></div>
</div>
</div>
js:
container.addEventListener('click',function(){
console.log('container bubble')
},false)
father.addEventListener('click',function(){
console.log('father bubble')
},false)
son.addEventListener('click',function(){
console.log('son bubble')
},false)
//执行顺序 son bubble ,father bubble, container bubble
事件捕获:(只有谷歌有,最新火狐有,IE没有捕获事件)结构上(非视觉上)嵌套关系的元素,会存在事件捕获的功能,即同一事件,自父元素捕获至子元素(事件源元素)。(自底向上)
container.addEventListener('click',function(){
console.log('container ')
},true)
father.addEventListener('click',function(){
console.log('father')
},true)
son.addEventListener('click',function(){
console.log('son')
},true)
//执行顺序 container , father, son
注意:触发事件元素son的冒泡和捕获事件是先看谁触发的(即从上往下谁先绑定的,谁就先触发事件,冒泡事件先绑定,先触发son bubble)
container.addEventListener('click',function(){
console.log('container bubble')
},false)
father.addEventListener('click',function(){
console.log('father bubble')
},false)
son.addEventListener('click',function(){
console.log('son bubble')
},false)
container.addEventListener('click',function(){
console.log('container ')
},true)
father.addEventListener('click',function(){
console.log('father')
},true)
son.addEventListener('click',function(){
console.log('son')
},true)
//执行顺序 container,
// father,
// son bubble,
// son,
// father bubble,
// container bubble
阻止事件冒泡:e.stopPropagation();
e.canceBubble=true;(IE9之前使用)
阻止默认事件:e.preventDefault();句柄方式绑定事件,则用return false;