Binding arrow keys in JS/jQuery

后端 未结 16 2115
春和景丽
春和景丽 2020-11-22 12:25

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

16条回答
  •  一个人的身影
    2020-11-22 13:13

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

    Check the above example here.

提交回复
热议问题