简体   繁体   中英

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.

This code works and I have tested on IE7, Firefox 10, Google Chrome 17 but I don't have the other browsers to test. 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.

IE6 is not a modern browser however, and it doesn't implement DOM Level 2 or preventDefault() . The alternative IE6 uses setting event.returnValue to false , as you did. Note that this will not affect event bubbling (in IE6 that would be accomplished by setting event.cancelBubble to 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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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