Binding arrow keys in JS/jQuery

后端 未结 16 2192
春和景丽
春和景丽 2020-11-22 12:25

How do I go about binding a function to left and right arrow keys in Javascript and/or jQuery? I looked at the js-hotkey plugin for jQuery (wraps the built-in bind function

16条回答
  •  被撕碎了的回忆
    2020-11-22 13:10

    document.onkeydown = function(e) {
        switch(e.which) {
            case 37: // left
            break;
    
            case 38: // up
            break;
    
            case 39: // right
            break;
    
            case 40: // down
            break;
    
            default: return; // exit this handler for other keys
        }
        e.preventDefault(); // prevent the default action (scroll / move caret)
    };
    

    If you need to support IE8, start the function body as e = e || window.event; switch(e.which || e.keyCode) {.


    (edit 2020)
    Note that KeyboardEvent.which is now deprecated. See this example using KeyboardEvent.key for a more modern solution to detect arrow keys.

提交回复
热议问题