如何在Javascript和/或jQuery中绑定函数到左和右方向键?我查看了jQuery的js-hotkey插件(包装了内置的bind函数以添加一个参数来识别特定的键),但它似乎不支持方向键。


当前回答

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

其他回答

咖啡和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()
$(document).keydown(function(e){
    if (e.which == 37) { 
       alert("left pressed");
       return false;
    }
});

字符编码:

37 -左 38岁以上 39 -对 40 -下降

纯js右转或左转的例子

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

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

            }
        });

防止箭头只适用于任何对象之外的选择,实际上我还没有在另一个对象上测试LOL。 但它可以停止页面和输入类型上的箭头事件。

我已经尝试阻止箭头左右改变选择对象的值使用“e.c preventdefault()”或“返回false”在“kepress”“keydown”和“keyup”事件,但它仍然改变对象的值。但是事件仍然告诉你箭头被按下了。

你可以使用方向键的keyCode(37,38,39和40表示左,上,右和下):

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

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

在这里检查上面的例子。