Javascript: different keyCodes on different browsers?

一曲冷凌霜 提交于 2019-11-28 06:55:24

See http://unixpapa.com/js/key.html for an explanation why they have different keys. I do not know of an international way to match keys.

It depends whether you're interested in which physical key the user has pressed or which character the user has typed. If it's the character you're after, you can get that reliably in all major browsers (using the keypress event's which property in most browsers or keyCode in IE <= 8), but only in the keypress event. If you're after the key, use the keydown or keyup event and examine the keyCode property, although the exact key-code mappings do differ somewhat between browsers.

An excellent explanation of and reference for all JavaScript key-related events can be found at http://unixpapa.com/js/key.html.

To detect the user typing a colon character reliably in all the major browsers, you could do the following:

document.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    if (charCode && String.fromCharCode(charCode) == ":") {
        alert("Colon!");
    }
};

This is an old question. The modern way to do this is use event.key. See MDN Key

ifroz

I think you should make JavaScript to get the keycode of the ':' character, so the script will know what is it in a certain environment. Similar question had been asked here, in stackoverflow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!