Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - action by key press

I'm designing a web based accounting software. I would like to open the "new accounting document" whenever the user press N key for example. And open "settings" whenever he/she is pressing S key.

I saw some scripts based on JavaScript and jQuery. But they did not work exactly. Can anyone help me please ?

I have tried this script:

var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
   //Do something
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$(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(); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...