Javascript keycode clash: “right arrow” and “single quote”

后端 未结 4 1207
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 07:06

The following script does what it should, that is, it reacts on the keys \"arrow left\" and \"arrow right\". However, due to a keycode clash, it reacts on a single quote as

4条回答
  •  星月不相逢
    2021-01-14 07:55

    When the user presses the single quote key, the e.keyCode property is zero, and the e.which property is 39. Executing String.fromCharCode(39) returns a single quote.

    You want the keyCode if that property is in the event object:

    var keycode = "keyCode" in e ? e.keyCode : e.which;
    

    That way you get zero for the keyCode when that property exists in the event object, and when the which property also exists.

    document.onkeydown = function(event) {
        event = event || window.event;
    
        var keyCode = "keyCode" in event ? event.keyCode : event.which;
    
        switch (keyCode) {
            case 37: console.log("37 was pressed", event); break;
            case 39: console.log("39 was pressed", event); break;
        }
    };
    

    Edit #1: Other commenters and answers are correct. I forgot you shouldn't be detecting control keys with keypress events. Changed to onkeydown.

    Full HTML example that works cross browser:

    
    
    
        
        Key Codes Test
    
    
        
        
    
    
    

提交回复
热议问题