javascript jQuery - 按下字符 - 与键盘无关
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7544826/
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
jQuery - get character pressed - REGARDLESS of Keyboard
提问by Stefan
I am trying to retrieve the character inserted into a textfield/input with jQuery.
我正在尝试使用 jQuery 检索插入到文本字段/输入中的字符。
I use the usual:
我使用通常的:
var character = String.fromCharCode( e.keyCode || e.which );
method, but the only problem occurs when I use a different keyboard layout which I just noticed.
方法,但唯一的问题是当我使用刚刚注意到的不同键盘布局时。
So for example, on a Standard US Keyboard it works perfectly. On a German Keyboard for instanece, if I have the language set to English - basically rendering it a standard US Keyboard, when I press the characters equivalent to :;'\,./[]=-
, I get the German characters I actually see on my keyboard (although the English equivalent of then is added to the input).
例如,在标准美式键盘上它可以完美运行。在德语键盘上,如果我将语言设置为英语 - 基本上将其渲染为标准的美国键盘,当我按下相当于 的字符时:;'\,./[]=-
,我会得到我在键盘上实际看到的德语字符(尽管当时的英语相当于被添加到输入中)。
Example: if I console.log( character )
for the folowing sentence I get:
示例:如果我console.log( character )
为以下句子我得到:
- In the input:
[]\';/.,
- In the console:
?YoTü???
- 在输入中:
[]\';/.,
- 在控制台中:
?YoTü???
My obvious question is, how can I make sure to get the true character inserter?
我很明显的问题是,我怎样才能确保获得真正的字符插入器?
回答by J?rgen
The keypress event is different from the keyup and keydown events as it contains the key actually pressed. Try using that instead. Check it out with this snippet:
keypress 事件与 keyup 和 keydown 事件不同,因为它包含实际按下的键。尝试使用它。用这个片段检查一下:
$('body').keypress(function(e){
console.log('keypress', String.fromCharCode( e.which ));
});
$('body').keyup(function(e){
console.log('keyup', String.fromCharCode( e.which ));
});
回答by pimvdb
What you can do is making the character appear in a hidden textbox and fetch the actual value. That way, you will get the character. You are currently passing the keycode as if it is a charactercode. They are not the same.
您可以做的是使字符出现在隐藏的文本框中并获取实际值。这样,您将获得角色。您当前正在传递密钥代码,就好像它是字符代码一样。他们不一样。
(function() {
var input = $("<input>").appendTo('body') // an hidden input element
.css({ position: "absolute",
left: -500,
top: -500 });
$('body').bind({ keydown: function(e) {
input.focus(); // make characters appear in input element
},
keyup: function() {
var value = input.val(); // get value when key pressed
input.val(""); // reset value of input element
if(value) {
alert(value); // if there is a value, display it
}
}
});
})();