在JS / jQuery中绑定箭头键

不打扰是莪最后的温柔 提交于 2020-02-27 04:17:45

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


#1楼

我只是结合了其他答案中的最佳方法:

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

#2楼

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

在此处签出库=> http://robertwhurst.github.com/KeyboardJS/


#3楼

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

字符代码:

37-左

38以上

39-对

40-下


#4楼

您可以使用箭头键的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;
  }
});

此处检查以上示例。


#5楼

您确定jQuery.HotKeys不支持箭头键吗? 当我在IE7,Firefox 3.5.2和Google Chrome 2.0.172中对其进行测试时,我已经弄乱了他们的演示,并观察到左右,上下的工作情况。

编辑 :看来jquery.hotkeys已重定位到Github: https : //github.com/jeresig/jquery.hotkeys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!