How to get LOCALIZED character on keypress?

后端 未结 2 2003
醉梦人生
醉梦人生 2021-02-15 12:45

I need to get localized character on keypress event. For example: on a Czech keyboard I need to get ř not 5 character (key code 53) (see Czech keyb

相关标签:
2条回答
  • 2021-02-15 13:17

    And make sure you are using 'keypress', but not 'keydown' event.

    If you use 'keydown' String.fromCharCode(event.keyCode || event.which), it won't return you a localised character. At least this was an issue for me on OS X with Chrome / FF.

    0 讨论(0)
  • 2021-02-15 13:28

    Using the keypress event will give you the character typed, regardless of keyboard layout.

    document.onkeypress = function(evt) {
        evt = evt || window.event;
        var charCode = evt.which || evt.keyCode;
        var charTyped = String.fromCharCode(charCode);
        alert("Character typed: " + charTyped);
    };
    

    Here's my usual link to Jan Wolter's excellent page documenting JavaScript key handling: http://unixpapa.com/js/key.html

    0 讨论(0)
提交回复
热议问题