How to get first pick at keydown (preventing “add bookmark” dialog from showing)

五迷三道 提交于 2019-12-11 01:47:26

问题


I have a checkbox in my jQuery application that you can check to duplicate a <div>. I'd like now to create a Ctrl+D shortcut for the operation. I can sense Ctrl+D with:

$(document).on('keydown',function(e) {  
    debugger;
    if((e.keyCode == 68) && e.ctrlKey){
        $('.duplicate').trigger('click');
    }
});  

But it looks like Firefox is capturing the Ctrl+D first and putting up a dialog to "Edit a bookmark."

How can I get the interrupt first, and then I'll kill it when I'm done? I don't want my users to have to dismiss a Firefox dialog every time they enter Ctrl+D.


回答1:


Try using e.preventDefault();:

$(document).on('keydown',function(e) {  
    //debugger;
    if((e.keyCode == 68) && e.ctrlKey){
        $('.duplicate').trigger('click');
        e.preventDefault();
    }
});  

See demo page here (edit the demo here).

On a side note, it is not a good usability practice to override widely-known keys/commands. While you can achieve that, it is advisable and better to use another combination of keys.




回答2:


Have you tried e.preventDefault();?

Or a better alternative - pick a different combination. Users typically don't like it when you start messing with their key bindings. On many sites (trello and github come to mind), there are no control keys at all. You can invoke special functionality just by typing a single character (on github "t" opens a page where you can type a filename and it will filter files in your repository). And in most cases that should be fine. You don't typically need to be able to type things on the html body. You would just want to make sure they're not inside an input or textarea before you fire the functionality.



来源:https://stackoverflow.com/questions/18522385/how-to-get-first-pick-at-keydown-preventing-add-bookmark-dialog-from-showing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!