Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用箭头键连续移动div_Javascript_Jquery_Html - Fatal编程技术网

Javascript 使用箭头键连续移动div

Javascript 使用箭头键连续移动div,javascript,jquery,html,Javascript,Jquery,Html,我发现一把小提琴在按下键盘上的箭头键时会移动一个div,但是每次都需要按下它才能获得流畅的移动 那么,如何像下面的示例那样移动div,但要按住箭头键 jQuery $(document).keydown(function(e) { switch (e.which) { case 37: $('div').stop().animate({ left: '-=50' }); //left arrow key break; case 38: $('di

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

那么,如何像下面的示例那样移动div,但要按住箭头键

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


这可能是您的一种方法:

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;
});
也许您必须更改变量
宽度
高度
,以满足您的需要


这可能是一种适合您的方法:

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;
});
也许您必须更改变量
宽度
高度
,以满足您的需要


您可以在按键时将变量设置为true,在放开按键时将变量设置为false

您可以在按键时将变量设置为true,在放开按键时将变量设置为false

我使用Chrome。按下箭头键并按住它实际上成功地连续向下移动了方块。你可以这样做(增加距离和增加时间)>>使用Chrome对我也有效,但移动的进度比我连续点击慢得多。我使用Chrome。按下箭头键并按住它实际上成功地连续向下移动了方块。你可以这样做(增加距离和增加时间)>>使用Chrome也适用于我,但是移动的进度要比我连续点击慢得多。好的一+1我在找答案好的一+1我在找答案欢迎来到SO和thx,谢谢你的回答。使用代码示例的答案通常更完整,请考虑添加代码:)欢迎使用SO和THX进行回答。使用代码示例的答案通常更完整,考虑添加代码:)。