admin管理员组文章数量:1389768
I try to convert keystrokes into chracters. In other question someone remand to use the onkeydown function because onkeypress gets handeled differently by different characters.
I don't know how to handle special chracters like ´ ` ' ( ) that might be different in different keyboards around the world.
I try to convert keystrokes into chracters. In other question someone remand to use the onkeydown function because onkeypress gets handeled differently by different characters.
I don't know how to handle special chracters like ´ ` ' ( ) that might be different in different keyboards around the world.
Share Improve this question asked Sep 16, 2009 at 22:39 ChristianChristian 26.5k43 gold badges140 silver badges231 bronze badges2 Answers
Reset to default 7For keys that have printable character equivalents, you should use the keypress
event because you can retrieve character codes from the keypress
event, which is generally not possible for keyup
and keydown
events.
The event properties you need are which
and keyCode
- pretty much all browsers have one or both of these, though IE muddies the waters by using keyCode
for the character code while some other browsers return a (different) key code. Most non-IE browsers also have charCode
but it seems all such browsers also have which
, so charCode
is never needed. A simple example:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
Here is a useful reference page.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
document.getElementById("label").style.display = "none";
if (e.keyCode == '65') {
//a
var lx = document.getElementById('location');
typeIt("a");
}
else if (e.keyCode == '66') {
//b
var lx = document.getElementById('location');
typeIt("b");
}
else if (e.keyCode == '67') {
//c
var lx = document.getElementById('location');
typeIt("c");
}
}
This should successfully convert the key code you press into a string letter, which you can use in a bigger function. It takes more time, but I found it is highly patible with most browsers and keyboards (whatever the language may be.) I used this code in a text editor project which would be distributed to friends in several countries, so I am certain it will work. Note: the function above only includes the letters "A", "B", and "C".
本文标签: Converting keystrokes gathered by onkeydown into characters in JavaScriptStack Overflow
版权声明:本文标题:Converting keystrokes gathered by onkeydown into characters in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744668817a2618698.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论