jQuery使用箭头键移动div

我正在尝试使用箭头键移动div。 我有以下代码,这对我不起作用。 你觉得它有什么问题吗? 在http://jsfiddle.net/N5Ltt/1/查看jsfiddle

$(document).keydown(function(e) { switch (e.which) { case 37: $('div').stop().animate({ left: '-= 10' }); //left arrow key break; case 38: $('div').stop().animate({ top: '-= 10' }); //up arrow key break; case 39: $('div').stop().animate({ left: '+= 10' }); //right arrow key break; case 40: $('div').stop().animate({ top: '+= 10' }); //bottom arrow key break; } }) 

您需要做两件事:

  1. 您的

    需要position: absolute或您的topleft属性不会执行任何操作。

  2. jQuery不知道'-= 10'是什么意思,但它确实理解'-=10' 。 您可能希望一直到'-=10px'因为这更常见,但px不是必需的。

更新小提琴: http : //jsfiddle.net/ambiguous/N5Ltt/2/

您按住箭头键时会看到动画停止,因为您在每个keydown上调用.stop并停止动画。 动画使用计时器和.stop停止计时器; 如果键盘的重复速率比计时器的第一次迭代快,则按住箭头键时不会发生动画。 你一次只能移动10px所以你可以使用.css进行10px的直接非动画移动:

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

非动画版: http : //jsfiddle.net/ambiguous/N5Ltt/3/