keycode is always zero in Chrome for Android

2020-02-04 06:44发布

I need to detect the keycode for a custom search box on my website, but the keycode always returns as zero on Chrome for Android (except for backspace, which returns 8). Has anyone else experienced this, and how did you get around it? Our website works on all mobile browsers except Chrome for Android because we can't detect a non-zero keycode or charcode.

I'm running Chrome 27.0.1453.90 on Android 4.1.2 Jelly Bean. The problem can be duplicated with something as simple as:
alert(event.keyCode);

9条回答
老娘就宠你
2楼-- · 2020-02-04 07:21

The true way to get the keyCode is to use

event.which

This property on event object is standardize the event.keyCode property. You can read about it also in jQuery documentation here or in MDN here

In other way, I have a lot of experience with keyboard events on android devices. Android browser has problems sometimes with keyboard events due to device fragmentation (different ROMs between devices or external keyboard apps). The best way is to try to use all the keyboard events (keydown, keyup and keypress) and compare every result to get the pressed key.

The best way is to use in "input" event and get all the time the last charter. The input event can control like in my answer here.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-04 07:22

below solution also work for me. might be useful for others also.

var getKeyCode = function (str) {
    return str.charCodeAt(str.length - 1);
}

document.getElementById("a").onkeyup = function (e) {
    var kCd = e.keyCode || e.which;
    if (kCd == 0 || kCd == 229) { //for android chrome keycode fix
        kCd = getKeyCode(this.value);
    }
    alert(kCd)
}
查看更多
来,给爷笑一个
4楼-- · 2020-02-04 07:24

If anybody still digging it.Problem appears on stock Samsung keyboard for android devices.

Instead use onkeyup.

查看更多
登录 后发表回答