The example in this article shares with you how to prevent bubbling and default event methods in js for your reference. The specific content is as follows
Prevent bubbling. A simple example of bubbling is that the son knows a secret message and tells his father. The father knows and tells his grandfather again. The level-by-level transmission causes confusion in the event. To prevent bubbling, the son is not allowed to tell his father. Of course I won't tell grandpa. The domo below is a good example.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box { width: 300px; height: 300px; background: red; display: none; } </style> <script type="text/javascript"> window.onload = function() { var btn = document.getElementById('btn'); var box = document.getElementById('box'); btn.onclick = function(ev) { var oEvent = ev || event; box.style.display = 'block'; //oEvent.cancelBubble = true;//高版本浏览器 stopBubble(oEvent); //在低版本的chrome和firefox浏览器中需要兼容性处理 //高版本chrome和firefox浏览器直接使用上面这行代码即可 } document.onclick = function() { box.style.display = 'none'; } } //阻止冒泡事件的兼容性处理 function stopBubble(e) { if(e && e.stopPropagation) { //非IE e.stopPropagation(); } else { //IE window.event.cancelBubble = true; } } </script> </head> <body> <input type="button" id="btn" value="语言" /> <div id="box"></div> </body> </html>
The effect I achieved is: click the button btn to make the box appear, and click elsewhere to make the box disappear.
If I don’t prevent bubbling, then first btn will trigger the click time to display the box, but since the box is included in the document, it will bubble up and trigger the click event of the document, and the box will disappear. The execution sequence of this event can be verified using alert in different click events. Regarding the compatibility processing of cancelBubble, compatibility processing is no longer required in higher versions of chrome and firefox. You can directly use oEvent.cancelBubble = true. The following compatibility processing to prevent browser events is also not required in higher versions of browsers.
Default event. That is, the functionality of the browser itself.
function preventDefa(e){ if(window.event){ //IE中阻止函数器默认动作的方式 window.event.returnValue = false; } else{ //阻止默认浏览器动作(W3C) e.preventDefault(); } }
This is a compatibility way of writing, but if you only need to support higher version browsers, then just one sentence is enough as above.
btn.onclick = function (){ return false; }