用箭头键连续移动div

时间:2015-01-13 12:40:41

标签: javascript jquery html

当我按下键盘上的箭头键时,我发现了一个移动div的小提琴,但是每次都需要按下才能获得流畅的动作。

那么你如何像下面的例子一样移动一个div,但是按下箭头键呢?

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

的jQuery

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

HTML

div{
  background:#ccc;
  height:100px;
  width:100px;
  position: absolute;
  top: 0;
  left: 0;
}

2 个答案:

答案 0 :(得分:5)

这可能是一种方法:

var pressed = false;
$(document).keydown(function(e) {
    if(!pressed){ //only start animation once
        width = $(this).width();
        height = $(this).height();
        switch (e.which) {
            case 37:
                $('div').stop().animate({
                    left: '-=' + width //allow the user the move the div over the whole doc
                }, 2000); //left arrow key
                break;
        // and so on
       }
    }
    pressed = true;
}).keyup(function(){
    $('div').stop(); // stop the current animation
    pressed = false;
});

也许您必须更改变量widthheight才能满足您的需求。

<强> DEMO

答案 1 :(得分:0)

您可以在按下键时将变量设置为true,并在键释放时将其设置为false

相关问题