Binding arrow keys in JS/jQuery

2018-12-31 14:24发布

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 to add an argument to recognize specific keys), but it doesn't seem to support arrow keys.

16条回答
何处买醉
2楼-- · 2018-12-31 14:37

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');
    }
});
查看更多
只若初见
3楼-- · 2018-12-31 14:38

You can use KeyboardJS. I wrote the library for tasks just like this.

KeyboardJS.on('up', function() { console.log('up'); });
KeyboardJS.on('down', function() { console.log('down'); });
KeyboardJS.on('left', function() { console.log('right'); });
KeyboardJS.on('right', function() { console.log('left'); });

Checkout the library here => http://robertwhurst.github.com/KeyboardJS/

查看更多
墨雨无痕
4楼-- · 2018-12-31 14:40

With coffee & Jquery

  $(document).on 'keydown', (e) ->
    switch e.which
      when 37 then console.log('left key')
      when 38 then console.log('up key')
      when 39 then console.log('right key')
      when 40 then console.log('down key')
    e.preventDefault()
查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 14:42

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.

查看更多
时光乱了年华
6楼-- · 2018-12-31 14:43

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) { 
       alert( "arrowkey pressed" );
       return false;
    }
});
查看更多
看淡一切
7楼-- · 2018-12-31 14:50

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
    }
});
查看更多
登录 后发表回答