简体   繁体   English

阻止默认操作但不停止事件传播

[英]Prevent default action but don't stop the event propagating

I need the code to work on IE6+, just wanted to check I haven't missed out support for any browsers.我需要在 IE6+ 上运行的代码,只是想检查一下我是否错过了对任何浏览器的支持。

This code works and I have tested on IE7, Firefox 10, Google Chrome 17 but I don't have the other browsers to test.这段代码有效,我已经在 IE7、Firefox 10、Google Chrome 17 上进行了测试,但我没有其他浏览器要测试。 What I want to know if anyone else has done this and know what the code is, have I missed support for any browser with my code:我想知道是否有其他人这样做并知道代码是什么,我是否错过了使用我的代码对任何浏览器的支持:

    if (!e) e = window.event;       
    e.returnValue = false;      
    if (e.preventDefault) e.preventDefault();           
    return false;

preventDefault() is a w3c DOM Level 2 standard, so it should be implemented by all modern browsers. preventDefault()是 w3c DOM Level 2 标准,所以它应该被所有现代浏览器实现。

IE6 is not a modern browser however, and it doesn't implement DOM Level 2 or preventDefault() .然而,IE6 不是现代浏览器,它没有实现 DOM Level 2 或preventDefault() The alternative IE6 uses setting event.returnValue to false , as you did.另一种 IE6 使用将event.returnValue设置为false ,就像您所做的那样。 Note that this will not affect event bubbling (in IE6 that would be accomplished by setting event.cancelBubble to true).请注意,这不会影响事件冒泡(在 IE6 中,这将通过将event.cancelBubble设置为 true 来实现)。 So your code as it is should work in IE6 as well as all modern browsers to prevent the default action without stopping propagation.所以你的代码应该可以在 IE6 以及所有现代浏览器中工作,以防止默认操作而不停止传播。

But I'd restructure the code to not set any properties on the event if you don't have to:但是,如果您不必:

if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM