javascript jQuery 使用箭头键移动 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7782266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:18:00  来源:igfitidea点击:

jQuery Move div with arrow keys

javascriptjquerycssarrow-keys

提问by Pinkie

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/

我正在尝试使用箭头键移动 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;
    }
})

回答by mu is too short

There are two things you need to do:

您需要做两件事:

  1. Your <div>needs position: absoluteor your topand leftproperties 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 pxisn't necessary.
  1. 您的<div>需要position: absolute或您topleft属性将不会做任何事情。
  2. jQuery 不知道什么'-= 10'意思,但它确实理解'-=10'. 您可能想要一路走下去,'-=10px'因为这更常见,但px不是必需的。

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

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

You're seeing the animation stop when you hold down an arrow key because you call .stopon each keydown and that stops the animation. The animation works using a timer and .stopstops 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:

当您按住箭头键时,您会看到动画停止,因为您调用.stop每个 keydown 并停止动画。动画使用计时器工作并.stop停止计时器;如果键盘的重复率比计时器的第一次迭代快,那么当您按住箭头键时不会发生动画。您一次只能移动 10 像素,因此您可以使用.css以下方法进行 10 像素的直接非动画移动:

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

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

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