時間冒泡就是說: 當(dāng)點擊子元素的時候, 父元素或者祖先元素如果也綁定了點擊事件, 那么父元素或者祖先元素的事件也會觸發(fā)響應(yīng)的事件.
事件傳播是從父到子
事件響應(yīng)是從子到父
示例代碼如下:
.fatherfather{
background-color: #80FF00;
width: 200px;
height: 200px;
padding: 40px;
}
.father{
width: 100px;
height: 100px;
background-color: #0094ff;
}
<div class="fatherfather" id="fatherfather">
<div class="father" id="father">
<button id="btn">點擊我</button>
</div>
</div>
window.onload = function () {
var fafa = document.getElementById('fatherfather');
var fa = document.getElementById('father');
var b = document.getElementById('btn');
fa.onclick = function(){
console.log("I'm father");
}
btn.onclick = function(event){
var event = event || window.event;
if (event.stopPropagation) { // 普通瀏覽器取消事件冒泡
console.log(1);
event.stopPropagation();// 阻止事件傳播
} else { // IE 取消時間冒泡
console.log(2);
event.cancelBubble = true;// 取消冒泡
}
console.log("I'm btn");
}
fafa.onclick = function () {
console.log('fafa');
}
document.onclick = function () {
console.log('document');
}
}