Javascript 按键时循环一个函数
我试图在Javascript中使用两个键上下移动div。其思想是,当按下某个键时,每次都会有一个函数循环并添加到div的“top”样式值中。基本功能正常,但我无法让它循环,也无法对按键做出任何反应 在Javascript中很难找到有关keypress处理的信息,似乎大多数人都使用jQuery来处理这个问题 我使用do while循环正确吗?有没有更好的方法来处理keydown和keydup事件 这是我的密码:Javascript 按键时循环一个函数,javascript,html,loops,onkeydown,onkeypress,Javascript,Html,Loops,Onkeydown,Onkeypress,我试图在Javascript中使用两个键上下移动div。其思想是,当按下某个键时,每次都会有一个函数循环并添加到div的“top”样式值中。基本功能正常,但我无法让它循环,也无法对按键做出任何反应 在Javascript中很难找到有关keypress处理的信息,似乎大多数人都使用jQuery来处理这个问题 我使用do while循环正确吗?有没有更好的方法来处理keydown和keydup事件 这是我的密码: var x = 0; console.log(x); function player
var x = 0;
console.log(x);
function player1MoveDown() {
var value = document.getElementById("player1").style.top;
value = value.replace("%", "");
value = parseInt(value);
value = value + 1;
value = value + "%";
document.getElementById("player1").style.top = value;
console.log(value);
} //moves paddle down; adds to paddle's 'top' style value
function player1MoveSetting() {
x = 1;
do {
setInterval(player1MoveDown(), 3000);
}
while (x == 1);
console.log(x);
} //paddle moves while x=1; runs player1MoveDown function every 3 seconds
function player1Stop() {
x = 0;
}
下面是HTML的相关部分:
不能将按键事件附加到
div
,除非它有选项卡索引
:
<div class="paddle" id="player1"
onkeydown="player1MoveSetting()"
onkeyup="player1Stop()"
tabindex="1"
>
</div>
……关于这一点:
var p1= document.getElementById('player1');
p1.style.top= parseInt(p1.style.top)+1+'%';
这将调用
player1MoveDown
的返回结果:
setInterval(player1MoveDown(), 3000);
由于player1MoveDown
不返回任何内容,因此它相当于
setInterval(null, 3000);
要每3秒钟调用一次函数,请执行以下操作:
setInterval(player1MoveDown, 3000);
这将创建一个无限循环:
x = 1;
do {
setInterval(player1MoveDown, 3000);
}
while (x == 1);
即使keyup
将全局x
设置为0,它也不会运行,因为循环永远不会结束
相反,创建一个timer
变量,该变量在keydown
上设置,在keydup
上清除。
完整的JavaScript代码
var timer;
function player1MoveDown() {
var p1= document.getElementById('player1');
p1.style.top= parseInt(p1.style.top)+1+'%';
console.log(p1.style.top);
}
function player1MoveSetting() {
if(timer) return;
timer= setInterval(player1MoveDown, 100);
}
function player1Stop() {
clearInterval(timer);
timer= null;
}
document.getElementById('player1').focus();
旁注:您可能不想使用
setInterval
而想使用requestAnimationFrame
来实现平滑的动画效果。试试这个完美的方法。谢谢你的解释,这很有帮助!
var timer;
function player1MoveDown() {
var p1= document.getElementById('player1');
p1.style.top= parseInt(p1.style.top)+1+'%';
console.log(p1.style.top);
}
function player1MoveSetting() {
if(timer) return;
timer= setInterval(player1MoveDown, 100);
}
function player1Stop() {
clearInterval(timer);
timer= null;
}
document.getElementById('player1').focus();