在JS/jQuery中绑定箭头键。

时间:2022-05-25 17:24:31

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.

如何将函数绑定到Javascript和/或jQuery中的左右箭头键?我查看了jQuery的js-hotkey插件(包装内嵌的绑定函数以添加一个参数来识别特定的键),但它似乎并没有支持箭头键。

16 个解决方案

#1


482  

$(document).keydown(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)
});

Put your custom code for the arrow keys between the corresponding case and break lines.

将您的自定义代码用于对应的情况和中断行之间的箭头键。

e.which is normalized by jQuery, so it works in all browsers. For a pure javascript approach, replace the first two lines with:

e。这是由jQuery标准化的,所以它在所有的浏览器中都能工作。对于纯javascript方法,替换前两行:

document.onkeydown = function(e) {
    e = e || window.event;
    switch(e.which || e.keyCode) {


(edit 2017)
If you feel fancy, you can use e.key instead of e.which or e.keyCode now. e.key is becoming a recommended standard, allowing you to check against strings: 'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown'. New browsers support it natively, check here.

(编辑2017年)如果你觉得很有想象力,你可以用e。关键不是e。或e。键码。e。关键是成为推荐标准,允许你检查字符串:“ArrowLeft”、“ArrowUp”、“ArrowRight”、“ArrowDown”。新的浏览器支持它,在这里检查。

#2


441  

$(document).keydown(function(e){
    if (e.keyCode == 37) { 
       alert( "left pressed" );
       return false;
    }
});

Character codes:

字符编码:

37 - left

37 -左

38 - up

38,

39 - right

39 -右

40 - down

40 -下

#3


101  

You can use the keyCode of the arrow keys (37, 38, 39 and 40 for left, up, right and down):

您可以使用箭头键(37、38、39和40来表示左、上、右和下):

$('.selector').keydown(function (e) {
  var keyCode = e.keyCode || e.which,
      arrow = {left: 37, up: 38, right: 39, down: 40 };

  switch (keyCode) {
    case arrow.left:
      //..
    break;
    case arrow.up:
      //..
    break;
    case arrow.right:
      //..
    break;
    case arrow.down:
      //..
    break;
  }
});

Check the above example here.

检查上面的示例。

#4


22  

This is a bit late, but HotKeys has a very major bug which causes events to get executed multiple times if you attach more than one hotkey to an element. Just use plain jQuery.

这有点晚了,但是热键有一个非常大的bug,如果您将多个热键连接到一个元素,那么将会多次执行事件。只使用纯jQuery。

$(element).keydown(function(ev) {
    if(ev.which == $.ui.keyCode.DOWN) {
        // your code
        ev.preventDefault();
    }
});

#5


16  

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();
});

#6


14  

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

您可以使用KeyboardJS。我像这样为任务编写了库。

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/

在这里签出这个库=> http://robertwhurst.github.com/KeyboardJS/。

#7


10  

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

使用普通Javascript的简洁解决方案(感谢Sygmoral建议的改进):

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

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

也看到https://*.com/a/17929007/1397061。

#8


9  

Are you sure jQuery.HotKeys doesn't support the arrow keys? I've messed around with their demo before and observed left, right, up, and down working when I tested it in IE7, Firefox 3.5.2, and Google Chrome 2.0.172...

你确定jQuery。热键不支持方向键?在IE7、firefox3.5.2和谷歌Chrome 2.0.172中测试时,我曾经摆弄过他们的演示,然后观察左、右、上、下工作。

EDIT: It appears jquery.hotkeys has been relocated to Github: https://github.com/jeresig/jquery.hotkeys

编辑:看来jquery。热键被重新定位到Github: https://github.com/jeresig/jquery.hotkeys。

#9


5  

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.

而不是使用返回false;如上面的示例所示,您可以使用。preventdefault ();这样做是一样的,但更容易理解和阅读。

#10


3  

You can use jQuery bind:

您可以使用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');
    }
});

#11


3  

Example of pure js with going right or left

纯js的例子,是向左或向右的。

        window.addEventListener('keydown', function (e) {
            // go to the right
            if (e.keyCode == 39) {

            }
            // go to the left
            if (e.keyCode == 37) {

            }
        });

#12


2  

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;
    }
});

#13


0  

prevent arrow only available for any object else SELECT, well actually i haven't tes on another object LOL. but it can stop arrow event on page and input type.

防止箭头只适用于其他对象选择,实际上我没有在另一个对象LOL上。但是它可以在页面和输入类型上停止箭头事件。

i already try to block arrow left and right to change the value of SELECT object using "e.preventDefault()" or "return false" on "kepress" "keydown" and "keyup" event but it still change the object value. but the event still tell you that arrow was pressed.

我已经尝试用“e.preventDefault()”或“return false”在“kepress”“keydown”和“keyup”事件中改变选择对象的值,但它仍然会改变对象的值。但是这个事件仍然告诉你,箭头被按下了。

#14


0  

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

一个健壮的Javascript库,用于捕获键盘输入和输入的键组合。它没有依赖关系。

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

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
    }
});

#15


0  

I came here looking for a simple way to let the user, when focused on an input, use the arrow keys to +1 or -1 a numeric input. I never found a good answer but made the following code that seems to work great - making this site-wide now.

我来这里寻找一种简单的方法,让用户在专注于输入时,使用箭头键+1或-1作为数字输入。我从来没有找到一个很好的答案,但是下面的代码看起来很有用——现在这个站点已经很好了。

$("input").bind('keydown', function (e) {
    if(e.keyCode == 40 && $.isNumeric($(this).val()) ) {
        $(this).val(parseFloat($(this).val())-1.0);
    } else if(e.keyCode == 38  && $.isNumeric($(this).val()) ) { 
        $(this).val(parseFloat($(this).val())+1.0);
    }
}); 

#16


-1  

With coffee & Jquery

咖啡& 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()

#1


482  

$(document).keydown(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)
});

Put your custom code for the arrow keys between the corresponding case and break lines.

将您的自定义代码用于对应的情况和中断行之间的箭头键。

e.which is normalized by jQuery, so it works in all browsers. For a pure javascript approach, replace the first two lines with:

e。这是由jQuery标准化的,所以它在所有的浏览器中都能工作。对于纯javascript方法,替换前两行:

document.onkeydown = function(e) {
    e = e || window.event;
    switch(e.which || e.keyCode) {


(edit 2017)
If you feel fancy, you can use e.key instead of e.which or e.keyCode now. e.key is becoming a recommended standard, allowing you to check against strings: 'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown'. New browsers support it natively, check here.

(编辑2017年)如果你觉得很有想象力,你可以用e。关键不是e。或e。键码。e。关键是成为推荐标准,允许你检查字符串:“ArrowLeft”、“ArrowUp”、“ArrowRight”、“ArrowDown”。新的浏览器支持它,在这里检查。

#2


441  

$(document).keydown(function(e){
    if (e.keyCode == 37) { 
       alert( "left pressed" );
       return false;
    }
});

Character codes:

字符编码:

37 - left

37 -左

38 - up

38,

39 - right

39 -右

40 - down

40 -下

#3


101  

You can use the keyCode of the arrow keys (37, 38, 39 and 40 for left, up, right and down):

您可以使用箭头键(37、38、39和40来表示左、上、右和下):

$('.selector').keydown(function (e) {
  var keyCode = e.keyCode || e.which,
      arrow = {left: 37, up: 38, right: 39, down: 40 };

  switch (keyCode) {
    case arrow.left:
      //..
    break;
    case arrow.up:
      //..
    break;
    case arrow.right:
      //..
    break;
    case arrow.down:
      //..
    break;
  }
});

Check the above example here.

检查上面的示例。

#4


22  

This is a bit late, but HotKeys has a very major bug which causes events to get executed multiple times if you attach more than one hotkey to an element. Just use plain jQuery.

这有点晚了,但是热键有一个非常大的bug,如果您将多个热键连接到一个元素,那么将会多次执行事件。只使用纯jQuery。

$(element).keydown(function(ev) {
    if(ev.which == $.ui.keyCode.DOWN) {
        // your code
        ev.preventDefault();
    }
});

#5


16  

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();
});

#6


14  

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

您可以使用KeyboardJS。我像这样为任务编写了库。

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/

在这里签出这个库=> http://robertwhurst.github.com/KeyboardJS/。

#7


10  

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

使用普通Javascript的简洁解决方案(感谢Sygmoral建议的改进):

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

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

也看到https://*.com/a/17929007/1397061。

#8


9  

Are you sure jQuery.HotKeys doesn't support the arrow keys? I've messed around with their demo before and observed left, right, up, and down working when I tested it in IE7, Firefox 3.5.2, and Google Chrome 2.0.172...

你确定jQuery。热键不支持方向键?在IE7、firefox3.5.2和谷歌Chrome 2.0.172中测试时,我曾经摆弄过他们的演示,然后观察左、右、上、下工作。

EDIT: It appears jquery.hotkeys has been relocated to Github: https://github.com/jeresig/jquery.hotkeys

编辑:看来jquery。热键被重新定位到Github: https://github.com/jeresig/jquery.hotkeys。

#9


5  

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.

而不是使用返回false;如上面的示例所示,您可以使用。preventdefault ();这样做是一样的,但更容易理解和阅读。

#10


3  

You can use jQuery bind:

您可以使用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');
    }
});

#11


3  

Example of pure js with going right or left

纯js的例子,是向左或向右的。

        window.addEventListener('keydown', function (e) {
            // go to the right
            if (e.keyCode == 39) {

            }
            // go to the left
            if (e.keyCode == 37) {

            }
        });

#12


2  

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;
    }
});

#13


0  

prevent arrow only available for any object else SELECT, well actually i haven't tes on another object LOL. but it can stop arrow event on page and input type.

防止箭头只适用于其他对象选择,实际上我没有在另一个对象LOL上。但是它可以在页面和输入类型上停止箭头事件。

i already try to block arrow left and right to change the value of SELECT object using "e.preventDefault()" or "return false" on "kepress" "keydown" and "keyup" event but it still change the object value. but the event still tell you that arrow was pressed.

我已经尝试用“e.preventDefault()”或“return false”在“kepress”“keydown”和“keyup”事件中改变选择对象的值,但它仍然会改变对象的值。但是这个事件仍然告诉你,箭头被按下了。

#14


0  

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

一个健壮的Javascript库,用于捕获键盘输入和输入的键组合。它没有依赖关系。

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

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
    }
});

#15


0  

I came here looking for a simple way to let the user, when focused on an input, use the arrow keys to +1 or -1 a numeric input. I never found a good answer but made the following code that seems to work great - making this site-wide now.

我来这里寻找一种简单的方法,让用户在专注于输入时,使用箭头键+1或-1作为数字输入。我从来没有找到一个很好的答案,但是下面的代码看起来很有用——现在这个站点已经很好了。

$("input").bind('keydown', function (e) {
    if(e.keyCode == 40 && $.isNumeric($(this).val()) ) {
        $(this).val(parseFloat($(this).val())-1.0);
    } else if(e.keyCode == 38  && $.isNumeric($(this).val()) ) { 
        $(this).val(parseFloat($(this).val())+1.0);
    }
}); 

#16


-1  

With coffee & Jquery

咖啡& 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()