KeyboardEvent.keyCode deprecated. What does this mean in practice?

前端 未结 6 1105
甜味超标
甜味超标 2020-12-23 02:36

According to MDN, we should most definitely not be using the .keyCode property. It is deprecated:

https://developer.mozilla.org/en-US/do

6条回答
  •  离开以前
    2020-12-23 03:03

    In addition that all of keyCode, which, charCode and keyIdentifier are deprecated :
    charCode and keyIdentifier are non-standard features.
    keyIdentifier is removed as of Chrome 54 and Opera 41.0
    keyCode returns 0, on keypress event with normal characters on FF.

    The key property :

     readonly attribute DOMString key
    

    Holds a key attribute value corresponding to the key pressed

    As of the time of this writing, the key property is supported by all major browsers as of : Firefox 52, Chrome 55, Safari 10.1, Opera 46. Except Internet Explorer 11 which has : non-standard key identifiers and incorrect behavior with AltGraph. More info
    If that is important and/or backward compatibility is, then you can use feature detection as in the following code :

    Notice that the keyvalue is different from keyCode or which properties in that : it contains the name of the key not its code. If your program needs characters' codes then you can make use of charCodeAt(). For single printable characters you can use charCodeAt(), if you're dealing with keys whose values contains multiple characters like ArrowUp chances are : you are testing for special keys and take actions accordingly. So try implementing a table of keys' values and their corresponding codes charCodeArr["ArrowUp"]=38, charCodeArr["Enter"]=13,charCodeArr[Escape]=27... and so on, please take a look at Key Values and their corresponding codes

    if(e.key!=undefined){
            var characterCode = charCodeArr[e.key] || e.key.charCodeAt(0);
        }else{
            /* As @Leonid suggeted   */
            var characterCode = e.which || e.charCode || e.keyCode || 0;
        }
            /* ... code making use of characterCode variable  */  
    

    May be you want to consider forward compatibility i.e use the legacy properties while they're available, and only when dropped switch to the new ones :

    if(e.which || e.charCode || e.keyCode ){
            var characterCode = e.which || e.charCode || e.keyCode;
        }else if (e.key!=undefined){
            var characterCode = charCodeArr[e.key] || e.key.charCodeAt(0);
        }else{
            var characterCode = 0;
        }
    

    See also : the KeyboardEvent.code property docs and some more details in this answer.

提交回复
热议问题