如何在 Javascript 中侦听键盘类型文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4368036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to listener the keyboard type text in Javascript?
提问by Tattat
I want to get the keyboard typed text, not the key code. For example, I press shift+f, I get the "F", instead of listen to two key code. Another example, I click F3, I inputted nothing. How can I know that in js? Thank you.
我想获得键盘输入的文本,而不是键码。比如我按shift+f,我得到的是“F”,而不是听两个键码。另一个例子,我点击F3,我什么也没输入。我怎么知道在 js 中?谢谢你。
回答by Tim Down
To do it document-wide, use the keypress
event as follows. No other currently widely supported key event will do:
要在文档范围内执行此操作,请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));
}
};
For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html
对于所有与 key 相关的 JavaScript 问题,我推荐 Jan Wolter 的优秀文章:http: //unixpapa.com/js/key.html
回答by capdragon
I use jQuery to do something like this:
我使用 jQuery 来做这样的事情:
$('#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
}
});
回答by Chris W. Rea
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 codeusing String.fromCharCode()
.
您可以监听onkeypress
事件。然而,而不是只检查要么event.keyCode
(IE)或event.which
(Mozilla的)属性,让你的关键代码,你需要转换的关键代码使用String.fromCharCode()
。
A good demo is at Javascript Char Codes (Key Codes). View the source and look for the displayKeyCode(evt)
function.
一个很好的演示是在Javascript Char Codes (Key Codes)。查看源代码并查找displayKeyCode(evt)
函数。
Additional references: w3schools - onkeypress Eventand w3schools - JavaScript fromCharCode() method.
其他参考:w3schools - onkeypress 事件和w3schools - JavaScript fromCharCode() 方法。
回答by Juan Mendes
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
这太复杂了,无法快速回答。这是我用作键盘处理的权威参考。http://unixpapa.com/js/key.html