action by key press

倖福魔咒の 提交于 2019-11-30 15:16:33
$(document).bind('keyup', function(e){
    if(e.which==78) {
      // "n"
    }
    if(e.which==83) {
      // "s"
    }
});

To prevent if an input is focused:

$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ $(document).bind('keyup', function(e){ etc.... });

You might want to put the bind function into its own function so you don't duplicate code. e.g:

function bindKeyup(){
    $(document).bind('keyup', function(e){
      if(e.which==78) {
        // "n"
      }
      if(e.which==83) {
        // "s"
      }
    });
}
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ bindKeyup(); });

You can detech keypresses in jQuery using either .keypress() or .keyup() methods, here is a quick example :

$(document).keyup(function(event) { // the event variable contains the key pressed
 if(event.which == 78) { // N keycode
   //Do something
 }
});

Here is a list of keycodes : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Update 1

.keyup and .keydown have different affects - as per comments from @ThomasClayson -: keyup is the best one to go for as keypress will repeat if the key is held down. it registers an event for each character inserted. It also doesn't register modifier keys such as shift (although not necessary here, it might be something to keep in mind)

Update 2

This is from the jQuery keyup doc site :

To determine which key was pressed, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows.

Affectively meaning that which.event is all you need to determine which key has been used. Thanks @nnnnnn

Rory McCrossan

You need to read up on the .keyCode() attribute of the event object. You can interrogate that to discover which key was pressed and act accordingly. I'd also suggest you add modifier keys to your shortcuts, such as Shift or Alt, so that when someone is innocently typing in an input, the panel doesn't pop up. In the example below I've used Shift

$(document).keyup(function(e) {
    if (e.shiftKey) {
        switch(e.keyCode ? e.keyCode : e.which) {
            case 78: // N pressed
                myNPressedHandler();
                break;
            case 83: // S pressed
                mySPressedHandler();
                break;
        }
    }
} 
$(document).bind('keypress', function(e) {
    var keycode= (e.keyCode ? e.keyCode : e.which);
       if(keyCode==78) {
      // "n"
    }else if(keyCode==83) {
      // "s"
    }

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