开发者

Javascript keycodes for Alt, Ctrl, and Shift

$("#text").bind('keypress', function(e) {
    var code = (e.KeyCode ? 开发者_运维知识库e.keyCode : e.which);  
    alert(code);
}

It works fine for everything except Alt, Ctrl, or Shift.

But in all tutorials that i found it should echos 17, 18, 19

Why?


use .keydown() or .keyup()

see it in action

jQuery(function($){
  var output = $('.output');
  $("#text1").bind('keypress', function(e) {
    var code = (e.KeyCode ? e.keyCode : e.which);  
    output.text(code);
  });
  $("#text2").bind('keydown', function(e) {
    var code = (e.KeyCode ? e.keyCode : e.which);  
    output.text(code);
  });
  $("#text3").bind('keyup', function(e) {
    var code = (e.KeyCode ? e.keyCode : e.which);  
    output.text(code);
  });
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
keypress <input type="text" id="text1"> <br>
keydown <input type="text" id="text2"> <br>
keyup <input type="text" id="text3">

<br><br>
Output: <span class="output"></span>


Have you considered using the jquery.hotkeys extension that allows you to bind by specifying a string?

"C-A-q" would bind you to: 

Control + Alt + q.


It would probably be better to use console.log to find them. You can also use just one textbox easily for this.

$("#textbox").keydown(function(e) {
    console.log("keydown: "+e.keyCode);
});

And do the same for keyup and keypress to see better how it all works.

Side note: JavaScript sure is hard to write on a phone ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜