admin管理员组文章数量:1335584
I am looking for a way to translate a keypress into the string corresponding to the chracter. Something like this:
$(document).keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
except that this code does not take into account capitalization and does not work for special character, e.g. ",". This:
$(document).keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
seems to the trick, but it can not prevent default browser actions (such as go back on backspace) and there seem to be browser patibly issues.
Is there any better way, that works across browsers and keyboard layouts ?
I am looking for a way to translate a keypress into the string corresponding to the chracter. Something like this:
$(document).keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
except that this code does not take into account capitalization and does not work for special character, e.g. ",". This:
$(document).keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
seems to the trick, but it can not prevent default browser actions (such as go back on backspace) and there seem to be browser patibly issues.
Is there any better way, that works across browsers and keyboard layouts ?
Share Improve this question edited Nov 6, 2011 at 15:20 Maarten asked Nov 6, 2011 at 14:37 MaartenMaarten 4,7594 gold badges32 silver badges37 bronze badges 03 Answers
Reset to default 5It's not possible to reliably get the character from the event.which
property at an event type other than keypress
.
If you're questioning that statement, use the demo at this page. The event.which
property can only be translated correctly at a keypress
event.
If you want to ignore capitals, use the .toLowerCase()
method.
It is not surprising that keydown
event is not giving you upper case characters, since it is controlled by SHIFT key, which may or may not be pressed at the time.
To prevent default browser action simply return false from your handler.
What browser patibility issues are you having?
You can use same trick to get character code corresponding to key pressed. To prevent default browser actions you can try this-
event.preventDefault(); //For all major browsers
event.returnValue = false; //For Internet Explorer
本文标签: javascriptTranslate KeyDown keycode to string (jQuery)Stack Overflow
版权声明:本文标题:javascript - Translate KeyDown keycode to string (jQuery) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742383982a2464655.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论