Binding arrow keys in JS/jQuery

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.


$(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:

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.


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

Character codes:

37 - left

38 - up

39 - right

40 - down


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

$('.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.

链接地址: http://www.djcxy.com/p/19524.html

上一篇: 使用jQuery在'输入'提交表单?

下一篇: 在JS / jQuery中绑定箭头键