欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > HTML >内容正文

HTML

阻止事件冒泡 阻止浏览器的默认行为

发布时间:2023/12/20 HTML 34 豆豆
生活随笔 收集整理的这篇文章主要介绍了 阻止事件冒泡 阻止浏览器的默认行为 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>阻止事件冒泡 阻止浏览器的默认行为</title> <style type="text/css"></style> </head> <body><button id="btn1">按钮1</button><input type="text" id="m-text"><script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script><script type="text/javascript">$(function() {function stopBubble(e) { //如果提供了事件对象,则这是一个非IE浏览器 if (e && e.stopPropagation) {//因此它支持W3C的stopPropagation()方法 e.stopPropagation(); } else {//否则,我们需要使用IE的方式来取消事件冒泡 window.event.cancelBubble = true; }} $('body').on('click', function() {console.log('body');});$('#btn1').on('click', function(e) {console.log('按钮1');stopBubble(e); //阻止冒泡});//阻止浏览器的默认行为 function stopDefault(e) { //阻止默认浏览器动作(W3C) if (e && e.preventDefault) {e.preventDefault(); } else { //IE中阻止函数器默认动作的方式 window.event.returnValue = false; }return false; } $('#m-text').on('keydown', function(e) {console.log(String.fromCharCode(e.keyCode));stopDefault(e);});});</script> </body> </html>

总结

以上是生活随笔为你收集整理的阻止事件冒泡 阻止浏览器的默认行为的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。