<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>事件冒泡</title>
</head>
<body>
<h4>bubbles cancelBubble stopPropagation() stopImmediatePropagation() 区别</h4>
<input type="text" id="test">
<button type="button" id="btn" style="height: 30px;width: 200px;">bubbles</button>
<button type="button" id="btn2" style="height: 30px;width: 200px;">阻止冒泡按钮</button>
<button type="button" id="btn3" style="height: 30px;width: 200px;">stopPropagation</button>
<button type="button" id="btn4" style="height: 30px;width: 200px;">stopImmediatePropagation</button>
<button type="button" id="btn5" style="height: 30px;width: 200px;">cancelBubble</button>
<script type="text/javascript">
// bubbles cancelBubble stopPropagation() stopImmediatePropagation() 区别
// 1.bubbles 返回布尔值 表示当前事件是否会冒泡,只读
// 注意 大部分事件都会冒泡 但是focus blur scroll事件不会冒泡
var btn = document.getElementById('btn');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
var btn5 = document.getElementById('btn5');
var test = document.getElementById('test');
btn.onclick = function(e) {
e = e || window.event;
console.log(e.bubbles);
}
test.onclick = function(e) {
e = e || window.event;
console.log(e.bubbles);
}
// 2.stopPropagation() 表示取消事件的进一步冒泡,无返回值
// 但是无法阻止同一事件的其他监听函数被调用
// ie8 浏览器不支持
btn2.onclick = function(e) {
e = e || window.event;
// 阻止冒泡
e.stopPropagation();
this.innerHTML = '阻止冒泡'
}
btn3.addEventListener('click', function(e) {
e = e || window.event;
e.stopPropagation();
this.innerHTML = '修改了'
});
btn3.addEventListener('click', function(e) {
e = e || window.event;
this.style.backgroundColor = 'lightblue';
});
// 上层事件 观察是否冒泡使用
document.body.onclick = function(e) {
e = e || window.event;
console.log('body');
}
// 3.stopImmediatePropagation() 既可以阻止冒泡,也可以阻止同一事件的其他监听函数被调用
btn4.addEventListener('click', function(e) {
e = e || window.event;
e.stopImmediatePropagation();
this.innerHTML = '修改了'
});
btn4.addEventListener('click', function(e) {
e = e || window.event;
this.style.backgroundColor = 'lightblue';
})
// 4.cancelBubble 属性用于阻止冒泡,可读写
// 默认值为false
// 当设置为true,cancelBubble可以取消事件冒泡
btn5.addEventListener('click', function(e) {
e = e || window.event;
e.cancelBubble = true;
this.innerHTML = '修改了'
});
</script>
</body>
</html>
阻止事件冒泡兼容写法
// 兼容 stopPropagation() stopImmediatePropagation() ie8不支持
// e.cancelBubble = true; 全浏览器都支持 不是标准写法
// 兼容写法
var handler = function (e) {
e = e || window.event;
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}