jQuery用箭头键移动div [英] jQuery Move div with arrow keys
问题描述
我试图使用箭头键移动div。我有以下代码,它不为我工作。你看到了什么错误。 在 http://jsfiddle.net/N5Ltt/1/ 查看jsfiddle
I'm trying to move a div using the arrow keys. I have the following code which is not working for me. Do you see anything wrong with it. Check jsfiddle at http://jsfiddle.net/N5Ltt/1/
$(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;
}
})
推荐答案
您需要做两件事:
- 您的
< div>
需要position:absolute
或您的top
和left
' - = 10'
意味着但是它理解' - = 10'
。你可能想要一直到' - = 10px'
,因为这更常见,但px
不是必要。
- Your
<div>
needsposition: absolute
or yourtop
andleft
properties won't do anything. - 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 thepx
isn't necessary.
更新的小提琴: http://jsfiddle.net/ambiguous/N5Ltt/2/
当您按住箭头时,动画停止键,因为您在每个键下调用 .stop
并停止动画。动画使用计时器, .stop
停止计时器;如果键盘的重复速率快于定时器的第一次迭代,则在按住箭头键时不会发生动画。您一次只能移动10像素,因此您可以使用 <$直接执行10px的非动画移动c $ c> .css :
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);
非动画版本: http://jsfiddle.net/ambiguous/N5Ltt/3/
这篇关于jQuery用箭头键移动div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!