代码描述:js兼容所有浏览器 阻止事件冒泡。js兼容所有浏览器阻止事件冒泡代码下载
事件冒泡是一把双刃剑,有有利的一面,也有不利的一面,在某些情况下需要阻止事件冒泡效果,但是由于低版本IE浏览器的存在所以兼容性是一个问题,下面通过代码实例介绍一下兼容所有浏览器的阻止事件冒泡的javascript代码。 先看一段代码实例:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <style type="text/css"> #box { width:300px; height:300px; background:red; margin:0px auto; overflow:hidden; } #inner { width:100px; height:100px; background:green; margin:0px auto; margin-top:125px; font-size:12px; } </style> <script type="text/javascript"> window.onload=function(){ var box=document.getElementById("box"); var inner=document.getElementById("inner"); box.onclick=function(){ inner.innerHTML="事件传递到父元素"; } inner.onclick=function(){ inner.innerHTML="事件仅在本元素"; } } </script> </head> <body> <div id="box"> <div id="inner"></div> </div> </body> </html>
以上代码中,点击子div的时候,事件能够传递给父元素,关于什么是事件冒泡可以参阅javascript事件冒泡简单介绍一章节。 代码修改如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <style type="text/css"> #box { width:300px; height:300px; background:red; margin:0px auto; overflow:hidden; } #inner { width:100px; height:100px; background:green; margin:0px auto; margin-top:125px; font-size:12px; } </style> <script type="text/javascript"> function stopBubble(e) { if(e&&e.stopPropagation) { e.stopPropagation(); } else { window.event.cancelBubble=true; } } window.onload=function(){ var box=document.getElementById("box"); var inner=document.getElementById("inner"); box.onclick=function(){ inner.innerHTML="事件传递到父元素"; } inner.onclick=function(ev){ var ev=ev||window.event; stopBubble(ev); inner.innerHTML="事件仅在本元素"; } } </script> </head> <body> <div id="box"> <div id="inner"></div> </div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能