String.fromCharCode在按键事件上不起作用 [英] String.fromCharCode not working on keydown event
问题描述
我想在按键事件中读取输入字符并尝试对其进行处理.当我尝试使用"String.fromCharCode(key);"将其转换为字符时它总是给我大写字母.
I am tyring to read the input characters on keydown event and try to process them. When I am triing to convert them into character using "String.fromCharCode(key);" Its always giving me the capital letters.
Upadte: 奇怪的是,如果我听"keypress"事件,代码就可以工作.这是什么原因.有人可以解释一下这个行为.
Upadte: Strangely the code works if I listen for "keypress" event. What is the reason for this. Could some one please explain this behavoir.
示例代码如下:
var inp = document.getElementById("ti");
inp.addEventListener("keydown", onKeyDown);
function onKeyDown(e) {
if (window.event) {
var key = window.event.keyCode;
} else {
var key = e.keyCode;
}
document.getElementById("output").innerHTML += String.fromCharCode(key);
}
在按键事件中读取角色的最佳做法是什么
推荐答案
我编写了一个名为 keysight 的模块分别将keypress
,keydown
和keyup
事件转换为字符和键.
I wrote a module called keysight that translates keypress
, keydown
, and keyup
events into characters and keys respectively.
示例:
inp.addEventListener("keydown", function(event) {
var character = keysight(event).char
document.getElementById("output").innerHTML += character
})
这篇关于String.fromCharCode在按键事件上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!