开发者

event.keyCode and charCode on safari gives "undefined" for german special signs

开发者 https://www.devze.com 2023-03-31 14:40 出处:网络
I am running that function on keyUp: function onKeyUpHandler(e) { if(!e) var e = window.event; var code;

I am running that function on keyUp:

function onKeyUpHandler(e) {
if(!e) var e = window.event;
var code;
if (e.keyCode) code = e.keyCode;
    else if (e.which) code 开发者_运维百科= e.which;
    else if (e.charCode) code = e.charCode;
if (code < 37 || code > 40) { // not arrows
    //do Stuff;
}

it works fine for all chars in most browsers, but Safari (especialy on iPad) gives code as "undefined" (so it doesn't "do stuff") for some special chars like german ä, ü, ß etc. so i cannot check if it's arrow. I am not sure if I should add "or (typeof(code) == 'undefined') ". Could you help me decide what should i do?


keyCode is the only property you need in keyup and keydown events. It works in all major browsers, including Safari. Here's a better version of your function. I'm not sure if there's another problem or not; let me know if there is.

function onKeyUpHandler(e) {
    e = e || window.event;
    var code = e.keyCode;
    if (code < 37 || code > 40) { // not arrows
        //do Stuff;
    }
}

Here is what I consider the definitive page on JavaScript key events: http://unixpapa.com/js/key.html

0

精彩评论

暂无评论...
验证码 换一张
取 消