1. 事件冒泡
(1)定义:事件的触发顺序自内向外,换句话说,就是从内层元素到外层元素
(2)案例
<div id="parent"> 父亲
<div id="child">孩子</div>
</div>
parent.addEventListener("click", function(){
console.log("parent");
})
child.addEventListener("click", function(event){
console.log("child");
})
点击“孩子”,输出结果
显然这不是我们想要的结果,我们想要点击“孩子”,输出child,而不是parent
(3)解决方式
- 通过阻止事件冒泡解决
parent.addEventListener("click", function(){
console.log("parent");
})
child.addEventListener("click", function(event){
// 阻止事件冒泡
stopBubble(event)
console.log("child");
})
function stopBubble(event){
if(event && event.stopPropagation){
// event.cancelBubble = true;
event.stopPropagation();
}else{
window.event.cancelBubble = true
}
}
stopBubble(event)
console.log("child");
})
function stopBubble(event){
if(event && event.stopPropagation){
// event.cancelBubble = true;
event.stopPropagation();
}else{
window.event.cancelBubble = true
}
}
阻止事件冒泡之后,再点击“孩子”,则只输出child
- 通过事件委托解决
document.addEventListener("click", function(event){
var target = event.target;
if (target == parent){
console.log("parent");
}
else if (target == child){
console.log("child");
}
})
2. 事件捕获
(1)定义:事件触发顺序变更为自外向内
(2)案例
parent.addEventListener("click", function(event){
console.log("parent");
}, true)
child.addEventListener("click", function(event){
console.log("child");
}, true)
(3)解决方式:通过事件委托
document.addEventListener("click", function(event){
var target = event.target;
if (target == parent){
console.log("parent");
}
else if (target == child){
console.log("child");
}
})