简体   繁体   中英

EventListener keydown is working but keyup isn't

EventListener keydown is working but keyup is (seemingly) not working. Here is my script:

var Keys = [];

var FrameLoop = window.requestAnimationFrame || 
window.webkitrequestAnimationFrame || window.mozrequestAnimationFrame || 
window.msrequestAnimationFrame;
window.requestAnimationFrame = FrameLoop;

window.onload = GameChange();

function GameChange() {
    if (Keys[39] == true) {
        alert("right");
    }
    FrameLoop(GameChange);
}

document.body.addEventListener("keydown", function(k) {
    Keys[k.keyCode] = true;
});

document.body.addEventListener("keyup", function(k) {
    Keys[k.keyCode] = false;
});

As one can see, the code is aiming to alert "right" when the right arrow is clicked and keep doing that till the right arrow key is released.

This is because alert() is script blocking.

This means that whatever script you were running when it has been called is paused at this call, until the user close the alert (same for all other prompt windows).

Add to this that the requestAnimationFrame schedule is executed before the event callbacks loop, and you have an infinite loop of alert() , except if you are able to close it before the next screen refresh (good luck with that) .

The easy solution, is to not use alert() (ever?). Instead, if you want to debug something in your code, use console.log which won't stop the normal execution of your script.

Your fixed snippet.

 var Keys = []; var FrameLoop = window.requestAnimationFrame || window.webkitrequestAnimationFrame || window.mozrequestAnimationFrame || window.msrequestAnimationFrame; window.requestAnimationFrame = FrameLoop; window.onload = GameChange(); function GameChange() { if (Keys[39] == true) { console.log("right"); } FrameLoop(GameChange); } document.body.addEventListener("keydown", function(k) { Keys[k.keyCode] = true; }); document.body.addEventListener("keyup", function(k) { Keys[k.keyCode] = false; console.log('keyup'); }); onfocus = function(){document.body.className="focus"}; onblur = function(){document.body.className=""}; 
 .focus > p {opacity: 0} 
 <p>click here to gain focus</p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM