简体   繁体   中英

keydown event not fired, why?

In JavaScript, I hold two keys down, and keydown is fired perfectly. When I release one of the keys, keyup is fired. So far so good. But I am still holding one key down, so why arent keydown fired? I need this to happen in my game. Am I doing something wrong? Is this the expected response? Is there a work around or something?

window.addEventListener("keydown",
function (e) {
    console.log('down');
}, false);

window.addEventListener('keyup',
function (e) {
    console.log('up');
}, false);

Looks to me like you're trying to do something like this:

 var down = false; var up = false; document.body.addEventListener('keydown', function (e) { if(e.which === 40) { down = true; } if(e.which === 38) { up = true; } }); document.body.addEventListener('keyup', function (e) { if(e.which === 40) { down = false; } if(e.which === 38) { up = false; } // logic here for one but not the other if(down && !up) { alert('down but not up!'); } }); 

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