标签:load 方法 window body lse http rop 示例 style
事件冒泡现象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件冒泡现象</title> <style> div{padding: 50px;} #div1{background: red;} #div2{background: blue;} #div3{background: yellow;} </style> <script> window.onload = function(){ var aDivs = document.getElementsByTagName(‘div‘); for(var i = 0; i < aDivs.length; i++){ aDivs[i].onclick = function(){ alert(this.id); } } } </script> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>
浏览器效果
阻止事件流的方法:
代码示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件冒泡阻止</title> <style> div{padding: 50px;} #div1{background: red;} #div2{background: blue;} #div3{background: yellow;} </style> <script> window.onload = function(){ var aDivs = document.getElementsByTagName(‘div‘); for(var i = 0; i < aDivs.length; i++){ aDivs[i].onclick = function(ev){ var e = ev || window.event; alert(this.id); stopBubble(e); } } } /*阻止事件冒泡 */ //e为事件对象 function stopBubble(e){ if(e.cancelBubble){ e.cancelBubble = true;//ie8一下阻止方法 }else{ e.stopPropagation();//其他浏览器阻止方法 } } /*---阻止事件冒泡---end*/ </script> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>
浏览器效果
总结
阻止事件流的固定写法
/* 事件冒泡的浏览器兼容写法 */ function stopBubble(e){ if(e.cancelBubble){ e.cancelBubble = true;//IE8一下阻止事件冒泡 }else{ e.stopPropagation();//其它浏览器阻止事件冒泡 } }
标签:load 方法 window body lse http rop 示例 style
原文地址:https://www.cnblogs.com/taohuaya/p/9597529.html