关于html中的冒泡事件

2021-04-08 10:30:28
### html事件冒泡: 点击子级元素接收到的事件后,会把子级接收到的事件传递给父级,从下到上依次触发,层层向上传递,直至window,要阻止子级元素的冒泡,我们需要在点击事件中使用e.stopPropagation()来阻止冒泡,此方法适用于chorme与火狐浏览器,在IE浏览器中需要使用e.cancelBubble()=true来阻止冒泡 ```html <body> <div id="grandPa"> <div id="father"> <div id="son"> <input type="button" value="click" /> </div> </div> </div> <script type="text/javascript"> var father = document.getElementById('father'); father.addEventListener('click', function () { alert('father'); }) var son = document.getElementById('son'); son.addEventListener('click', function (e) { alert('son'); //停止冒泡,仅会alert son,否则将会依次alert "son" "father" e.stopPropagation() }); </script> </body> ```