企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
* 事件冒泡:在p元素上发生click事件的顺序应该是p -> div -> body -> html -> document * 事件捕获:在p元素上发生click事件的顺序应该是document -> html -> body -> div -> p ## **事件捕获** ``` <style type="text/css"> #myDiv { width: 100px; height: 100px; background-color: #FF0000; } </style> <body> <div id="myDiv"></div> <script type="text/javascript"> var div = document.getElementById("myDiv"); div.addEventListener("click", function (event) { alert("div"); }, true); document.body.addEventListener("click", function (event) { alert("body"); }, true); </script> </body> ``` ## **事件冒泡** ``` <style type="text/css"> #myDiv { width: 100px; height: 100px; background-color: #FF0000; } </style> <div id="myDiv"></div> <script type="text/javascript"> var div = document.getElementById("myDiv"); div.onclick = function (event) { alert("div"); }; document.body.onclick = function (event) { alert("body"); }; </script> ``` ## 阻止事件冒泡和事件捕获 `<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>` ``` <style> .one{ width: 200px; height: 200px; background: indianred } .two{ width: 100px; height: 100px; background: khaki; } </style> ``` ``` <script> var one = document.getElementsByClassName("one")[0]; var two = document.getElementsByClassName("two")[0]; one.addEventListener("click",function(){ console.log("one") },true)//加上true是事件捕获,默认是false是事件冒泡 two.addEventListener("click",function(e){ console.log("two") //e.stopPropagation();阻止事件冒泡 }) </script> ```