事件冒泡現象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(){ alert(this.id); } } } </script> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>
瀏覽器效果瀏覽器
阻止事件流的方法:this
代碼示例:spa
<!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>
瀏覽器效果code
總結htm
阻止事件流的固定寫法對象
/* 事件冒泡的瀏覽器兼容寫法 */ function stopBubble(e){ if(e.cancelBubble){ e.cancelBubble = true;//IE8一下阻止事件冒泡 }else{ e.stopPropagation();//其它瀏覽器阻止事件冒泡 } }