gpt4 book ai didi

javascript - 用方向键连续移动div

转载 作者:行者123 更新时间:2023-11-28 13:27:29 24 4
gpt4 key购买 nike

我发现了一个 fiddle ,可以在按下键盘上的箭头键时移动 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;
}

最佳答案

这可能是适合您的方法:

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;
});

也许您必须更改变量宽度高度以满足您的需求。

<强> DEMO

关于javascript - 用方向键连续移动div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27922430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com