如何在Javascript中监听键盘类型文本?

Tat*_*tat 8 javascript events javascript-events

我想获得键盘输入的文本,而不是键码.例如,我按shift + f,我得到"F",而不是听两个关键代码.另一个例子,我点击F3,我什么都没输入.我怎么知道在js?谢谢.

Tim*_*own 20

要在文档范围内执行此操作,请keypress按如下方式使用事件.目前没有其他广泛支持的关键事件可以做到:

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));
    }
};
Run Code Online (Sandbox Code Playgroud)

对于所有与密钥相关的JavaScript问题,我推荐Jan Wolter的优秀文章:http://unixpapa.com/js/key.html


cap*_*gon 2

我使用 jQuery 来做这样的事情:

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

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

});
Run Code Online (Sandbox Code Playgroud)

编辑:由于您没有绑定到文本框,因此使用:

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

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

});
Run Code Online (Sandbox Code Playgroud)

http://docs.jquery.com/Main_Page