简体   繁体   中英

Move item with arrow keys and jQuery

I have an item that can be dragged within a shape. I had been also able to move the item with the arrow keys on the keyboard, using:

$(document).bind('keypress', function(event) {
  if(event.which === 63232){ // up arrow key
    if(!event.shiftKey) howMuch = -1;   
    else if(event.shiftKey) howMuch = -10;   
    moveText(howMuch);   
  }
});

But, at least in FF, this doesn't work anymore. I alerted out the event that is happening on an arrow press and all four return zero.

How can I detect an arrow key press? Oh yeah...javascript or jQuery.

Thank you for your time, Todd

The keycode you're using is wrong, the up arrow is 38:

$(document).bind('keypress', function(event) {
    if (event.which === 38) {
        moveText(event.shiftKey ? -10 : -1);   
    }
});

Arrow keycodes for reference:

  • Left: 37
  • Up: 38
  • Right: 39
  • Down: 40

To find other keycodes check the example for keyPress() in the API

Isn't it just:

$(document).on('keypress', function(e) { // Note I used .on()
    if (e.keyCode == 38) {                // I never use .which
        howMuch = (e.shiftKey) ? -10 : -1;
    }
    moveText(howMuch); // never seen this function before, isn't that it?
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM