Binding arrow keys in JS/jQuery

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

    Instead of using return false; as in the examples above, you can use e.preventDefault(); which does the same but is easier to understand and read.

    0 讨论(0)
  • 2020-11-22 13:22

    A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

    http://jaywcjlove.github.io/hotkeys/

    hotkeys('right,left,up,down', function(e, handler){
        switch(handler.key){
            case "right":console.log('right');break
            case "left":console.log('left');break
            case "up":console.log('up');break
            case "down":console.log('down');break
        }
    });
    
    0 讨论(0)
  • 2020-11-22 13:26

    You can use jQuery bind:

    $(window).bind('keydown', function(e){
        if (e.keyCode == 37) {
            console.log('left');
        } else if (e.keyCode == 38) {
            console.log('up');
        } else if (e.keyCode == 39) {
            console.log('right');
        } else if (e.keyCode == 40) {
            console.log('down');
        }
    });
    
    0 讨论(0)
  • 2020-11-22 13:29

    A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):

    document.onkeydown = function(e) {
        switch (e.keyCode) {
            case 37:
                alert('left');
                break;
            case 39:
                alert('right');
                break;
        }
    };
    

    Also see https://stackoverflow.com/a/17929007/1397061.

    0 讨论(0)
提交回复
热议问题