简体   繁体   English

按下键时如何触发事件

[英]How can I fire a event when a key is pressed down

I have tried the code before, but when I hold down W it repeats the code, but I want to so if I hold it down, it will only execute the code one.我之前尝试过代码,但是当我按住 W 时它会重复代码,但我想这样做,如果我按住它,它只会执行代码之一。

window.addEventListener("keydown", checkKeyPressW, false);

var player = document.getElementById("player");

var leftMarginCounter = 0;
var bottomMarginCounter = 0;

var leftMarginCounterToString = "";

function checkKeyPressA_D(keyPressed) {
    if(keyPressed.keyCode == "97") {
        if(player.style.marginLeft != "0px") {
            leftMarginCounter = leftMarginCounter - 1;
            leftMarginCounterToString = leftMarginCounter.toString();
            leftMarginCounterToString = leftMarginCounterToString + "px";
            player.style.marginLeft = leftMarginCounterToString;
        }
    }
    else if(keyPressed.keyCode == "100") {
        if(player.style.marginLeft != "1316px") {
            leftMarginCounter = leftMarginCounter + 1;
            leftMarginCounterToString = leftMarginCounter.toString();
            leftMarginCounterToString = leftMarginCounterToString + "px";
            player.style.marginLeft = leftMarginCounterToString;
        }
    }
};

function checkKeyPressW(keyPressedW) {
    if(keyPressedW.keyCode == "87") {
        console.log("Pressed w");
    }
}

JS demo: https://jsfiddle.net/utnqeLmf/1/ JS演示: https://jsfiddle.net/utnqeLmf/1/

Code:代码:

 window.addEventListener("keydown", checkKeyPressW,  {
      once : true
 });

From the docs 从文档

once A Boolean indicating that the listener should be invoked at most once after being added.一次 A Boolean 表示添加后最多调用一次监听器。 If true, the listener would be automatically removed when invoked.如果为 true,则侦听器将在调用时自动删除。

EDIT编辑

If you want to avoid continuous key consoling when having the key pressed then change the event to keyup如果您想在按下按键时避免连续按键安慰,请将事件更改为 keyup

window.addEventListener("keyup", checkKeyPressW);

There is a property called repeat that returns true if the key is being held down有一个名为 repeat 的属性,如果按键被按住,则返回 true

document.addEventListener('keydown', (event) => {
   if(event.repeat) {
      // key is being held down
   } else {
      // key is being pressed
   }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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