如何在用户按"keydown“时移动元素,如果用户按"keyup”停止动画(移动),这是我现在的代码
$(document).ready(function(){
function checkKey(e){
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keydown (checkKey);
} else {
$(document).keydown (checkKey);
}
})我想在用户按下键(向下,向左,向上,向右)的同时移动立方体,而不是每次按下,这是可能的吗?
发布于 2012-05-27 22:08:48
你需要一个简单的2D引擎来设置一个游戏循环。
简单演示:http://jsfiddle.net/kzXek/
来源:https://github.com/superrob/simple-2D-javascript-engine/blob/master/simple2d.html
发布于 2012-05-27 21:07:39
那是你要找的吗?
$(document).on("keyup", function() {
$("#cube").stop(true);
});演示: http://jsfiddle.net/LjGRe/
发布于 2012-05-27 21:08:48
您只需更改checkKey函数,并在其中添加以下内容:
function checkKey(e){
$(document).keyup(return);
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}https://stackoverflow.com/questions/10774187
复制相似问题