jQuery Move div with arrow keys

南笙酒味 提交于 2019-11-29 04:53:04

There are two things you need to do:

  1. Your <div> needs position: absolute or your top and left properties won't do anything.
  2. jQuery doesn't know what '-= 10' means but it does understand '-=10'. You might want to go all the way to '-=10px' as that's more common but the px isn't necessary.

Updated fiddle: http://jsfiddle.net/ambiguous/N5Ltt/2/

You're seeing the animation stop when you hold down an arrow key because you call .stop on each keydown and that stops the animation. The animation works using a timer and .stop stops the timer; if the keyboard's repeat rate is faster than the first iteration of the timer then no animation happens when you hold down an arrow key. You're only moving by 10px at a time so you could just do a straight non-animated move by 10px using .css:

$div.css('left', $div.offset().left - 10);

Non-animated version: http://jsfiddle.net/ambiguous/N5Ltt/3/

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