欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

事件冒泡 bubbles cancelBubble stopPropagation() stopImmediatePropagation() 区别

发布时间:2023/12/13 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 事件冒泡 bubbles cancelBubble stopPropagation() stopImmediatePropagation() 区别 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
<!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;}}

 

总结

以上是生活随笔为你收集整理的事件冒泡 bubbles cancelBubble stopPropagation() stopImmediatePropagation() 区别的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。