开发者

How to listener the keyboard type text in Javascript?

I want to get the keyboard typed text, not the key code. For example, I press shift+f, I 开发者_如何学Pythonget the "F", instead of listen to two key codes. Another example, I click F3, I input nothing. How can I know that in js?


To do it document-wide, use the keypress event as follows. No other currently widely supported key event will do:

document.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    if (charCode) {
        alert("Character typed: " + String.fromCharCode(charCode));
    }
};

For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html


I use jQuery to do something like this:

$('#searchbox input').on('keypress', function(e) {

    var code = (e.keyCode ? e.keyCode : e.which);
  if(code == 13) { 
           //Enter keycode
     //Do something
  }

});

EDIT: Since you're not binding to text box use:

$(window).on('keypress', function(e) {

    var code = (e.keyCode ? e.keyCode : e.which);
  if(code == 13) { 
           //Enter keycode
     //Do something
  }

});

http://docs.jquery.com/Main_Page


You can listen for the onkeypress event. However, instead of just examining either the event.keyCode (IE) or event.which (Mozilla) property which gives you the key code, you need to translate the key code using String.fromCharCode().

A good demo is at Javascript Char Codes (Key Codes). View the source and look for the displayKeyCode(evt) function.

Additional references: w3schools - onkeypress Event and w3schools - JavaScript fromCharCode() method.


This is too complicated to answer quickly. This is what I use as the definitive reference for keyboard handling. http://unixpapa.com/js/key.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜