-->

e.preventDefault(); behaviour not working in Firef

2019-03-02 17:03发布

问题:

I have this basic function for handling the key event, everything works great. However, in Firefox 9.0.1 it seems I can't prevent the default event which is showing of bookmarks.

Is there any solution to prevent the default behaviour in FF?

$(document).keydown(function(evt) {     
    if (evt.which == 66 && evt.ctrlKey) {                             
         if (evt.preventDefault) {
             evt.preventDefault();
         } else {
             evt.returnValue = false;
         }    
         alert("Ctrl+B pressed");
         return false;                      
    }
});

回答1:

Seems like some sort of bug regarding alert. Try this:

$(document).keydown(function(evt) {     
    if (evt.which == 66 && evt.ctrlKey) {                             
         if (evt.preventDefault) {
             evt.preventDefault();
         } else {
             evt.returnValue = false;
         }    
         console.log("Ctrl+B pressed");
         return false;                      
    }
});

Doesn't open the Bookmarks Toolbar for me now. I assume you don't actually want to alert do you? I think you can just call your method as long as it doesn't contain an alert.