Binding arrow keys in JS/jQuery

后端 未结 16 2111
春和景丽
春和景丽 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:04

    I've simply combined the best bits from the other answers:

    $(document).keydown(function(e){
        switch(e.which) {
            case $.ui.keyCode.LEFT:
            // your code here
            break;
    
            case $.ui.keyCode.UP:
            // your code here
            break;
    
            case $.ui.keyCode.RIGHT:
            // your code here
            break;
    
            case $.ui.keyCode.DOWN:
            // your code here
            break;
    
            default: return; // allow other keys to be handled
        }
    
        // prevent default action (eg. page moving up/down)
        // but consider accessibility (eg. user may want to use keys to choose a radio button)
        e.preventDefault();
    });
    

提交回复
热议问题