最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Translate KeyDown keycode to string (jQuery) - Stack Overflow

programmeradmin0浏览0评论

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 0
Add a ment  | 

3 Answers 3

Reset to default 5

It'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
发布评论

评论列表(0)

  1. 暂无评论