Javascript 使用箭头键连续移动div
我发现一把小提琴在按下键盘上的箭头键时会移动一个div,但是每次都需要按下它才能获得流畅的移动 那么,如何像下面的示例那样移动div,但要按住箭头键 jQueryJavascript 使用箭头键连续移动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
$(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进行回答。使用代码示例的答案通常更完整,考虑添加代码:)。