阻止事件冒泡的两种方式
事件冒泡:开始时由最具体的元素接收,让后逐级向上传播到DOM最顶层节点
事件冒泡本身的特性,会带来的坏处,也会带来的好处,需要我们灵活掌握。
阻止事件冒泡:
标准写法:利用事件对象里面的stopPropagation()方法
非标准写法:IE6-8利用事件对象cancelBubble属性
代码示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .father { background-color: pink; width: 500px; height: 500px; } .son { background-color: purple; width: 200px; height: 200px; } </style> </head> <body> <div class="father"> <div class="son">son盒子</div> </div> </body> <script> var son = document.querySelector('.son') son.addEventListener('click', function (e) { alert('son') // 阻止冒泡 e.stopPropagation(); e.cancelBubble = true; }, false) var father = document.querySelector('.father') father.addEventListener('click', function () { alert('father') }, false) document.addEventListener('click', function () { alert('document') }) </script> </html>