当按键按下时循环函数

5
我正在尝试使用JavaScript来通过两个键使一个div上下移动。我的想法是,在某个键按下的同时,函数循环并每次将值添加到div的“top”样式中。基本函数可用,但我无法使其循环,并且无法让任何内容响应键按下事件。
在JavaScript中很难找到有关按键处理的信息,似乎大多数人使用jQuery来处理它。
我的do-while循环使用是否正确?是否有更好的方法来处理keydown和keyup事件?
这是我的代码:
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 class="paddle" id="player1" style="top:1%" onkeydown="player1MoveSetting()" onkeyup="player1Stop()"></div>


1
小提示:在编写平滑动画时,您可能希望使用requestAnimationFrame而不是setInterval - Mike 'Pomax' Kamermans
2
尝试这个:https://dev59.com/ZFPTa4cB1Zd3GeqPkY0X - frunkad
1个回答

6

除非 div 具有 tabindex,否则无法将键盘按下事件附加到它上面:

<div class="paddle" id="player1" 
     onkeydown="player1MoveSetting()"
     onkeyup="player1Stop()"
     tabindex="1"
>
</div>

你可以替换掉所有这段代码:
var value = document.getElementById("player1").style.top;
value = value.replace("%", "");
value = parseInt(value);
value = value + 1;
value = value + "%";
document.getElementById("player1").style.top = value;

使用以下方法:

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 上设置并在 keyup 上清除。
完整的 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();

Working Fiddle


1
太好了。谢谢你的解释,帮了我很多! - Blando

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接