js阻止事件冒泡

    xiaoxiao2021-03-25  79

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>阻止事件冒泡</title> <style> #outer{ width:500px; height:300px; background-color: green; color:#fff; position: absolute; left:50%; top:50%; transform: translate(-50%, -50%);/*利用了不定宽高水平垂直居中法*/ } #inner{ width:200px; height:100px; position: absolute; left:250px; top:150px; margin: -50px 0 0 -100px; background-color: blue;/*利用了已知宽高水平垂直居中法*/ } </style> </head> <body> <div id="outer">我是外层div <div id="inner">我是内层div</div> </div> <script> var out_div = document.getElementById('outer'); var in_div = document.getElementById('inner'); document.onclick = function(){ alert("document被点击"); } out_div.onclick = function(){ alert("外部div被点击"); } in_div.onclick = function(ev){ var oEvent = ev || event; /*这一句这么写是要兼容各个浏览器,在FireFox浏览器中,事件绑定的函数要获取到事件本身,需要从函数中传入,而IE等浏览器则可以直接使用event或者window.event得到事件本身。*/ oEvent.stopPropagation(); alert("内部div被点击"); } // stopPropagation()除IE8及其以下浏览器都兼容 </script> </body> </html>

    chrome浏览器下

    FireFox浏览器下

    opera浏览器下

    IE11浏览器下

    转载请注明原文地址: https://ju.6miu.com/read-33112.html

    最新回复(0)