[removed] different keyCodes on different browsers?

前端 未结 4 1349
我在风中等你
我在风中等你 2020-12-08 21:53

So I\'ve seen some forums posts about different browsers reporting differenct keyCodes, but everyone seems so avoid the \"why?\".

I was trying to capture the colon (

4条回答
  •  无人及你
    2020-12-08 22:37

    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!");
        }
    };
    

提交回复
热议问题