Kul*_*box 0 html javascript jquery
当我按下键盘上的箭头键时,我发现了一个移动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;
}
});
Run Code Online (Sandbox Code Playgroud)
HTML
div{
background:#ccc;
height:100px;
width:100px;
position: absolute;
top: 0;
left: 0;
}
Run Code Online (Sandbox Code Playgroud)
这可能是一种方法:
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;
});
Run Code Online (Sandbox Code Playgroud)
也许你必须改变变量width并height适应你的需要.