事件捕获和冒泡
-
事件捕获
事件捕获和冒泡
-
事件捕获
addEventListener第三个参数为true
-
格式:
<div class="father"> <div class="son"></div> </div> <script> let oFather = document.querySelector(".father"); let oSon = document.querySelector(".son"); oFather.addEventListener("click", function () { console.log("father"); }, true); oSon.addEventListener("click", function () { console.log("son"); }, true); //先打印father再打印son </script>
-
事件冒泡
addEventListener第三个参数为false,默认为false
-
格式:
<div class="father"> <div class="son"></div> </div> <script> let oFather = document.querySelector(".father"); let oSon = document.querySelector(".son"); oFather.addEventListener("click", function () { console.log("father"); }, false); oSon.addEventListener("click", function () { console.log("son"); }, false); //先打印son再打印father </script>
- 注意:on事件名和attachEvent都只接受两个参数,都是冒泡事件
-
阻止事件冒泡
-
格式:
<div class="father"> <div class="son"></div> </div> <script> let oFather = document.querySelector(".father"); let oSon = document.querySelector(".son"); oFather.onclick = function () { console.log("father"); } oSon.onclick = function (event) { event = event || window.event; //兼容写法 if (event.cancelBubble) { event.cancelBubble = true; } else { event.stopPropagation(); //IE9以上才支持 } console.log("son"); } </script>