简体   繁体   English

按键事件未在右箭头键上触发

[英]keypress event not firing on right arrow key

I have setup a keypress event that should fire when the user clicks the right arrow key on the keyboard.我已经设置了一个按键事件,当用户单击键盘上的右箭头键时应该触发该事件。 For some reason it is not firing.由于某种原因,它没有开火。 Using Chrome dev tools confirms event is not firing.使用 Chrome 开发工具确认事件没有触发。 When the user presses the right key it should insert an image onto the webpage (and delete another image).当用户按下右键时,它应该在网页上插入一张图片(并删除另一张图片)。

There is quite a lot of code so I apologise but I will only put in what I feel is relevant.有很多代码,所以我很抱歉,但我只会输入我认为相关的内容。

Here is the event listener:这是事件侦听器:

 document.addEventListener("keypress", (event) => {
                if (event.keycode === 39 || event.which === 39) {
                    newPosition = `box-${currentPos + 1}`;
                    naviCtrl.removeCharacter(DOMstrings);
                    naviCtrl.rightBtn(currentPos, chosenCharacter, newPosition);
                }
            });

Here is the rightBtn method:这是rightBtn方法:

 rightBtn: (currentPos, chosenCharacter, newPosition) => {
                if (newPosition.style.border-left === "none" && currentPos.style.border-right === "none") {
                    document.getElementById(newPosition).insertAdjacentHTML("beforeend", '<img class="character-img character-box" src="' + chosenCharacter + '">');
                    console.log(newPosition);

The event listeners are setup when the page loads with this init function:使用此 init function 加载页面时设置事件侦听器:

 return {
        init: () => { 
            setupEventListeners() 
        }
    };

You can see, this method is called globally here:可以看到,这个方法在这里被全局调用:

appController.init();

The event listener keypress is deprecated , as is event.which .事件侦听keypress已弃用event.which也是如此 You should use (probably) use keydown in this instance, and the correct keycode for right arrow ( ArrowRight ), as follows:在这种情况下,您应该(可能)使用keydown ,以及右箭头 ( ArrowRight ) 的正确键码,如下所示:

document.addEventListener("keydown", (event) => {
  if (event.keycode === "ArrowRight" || event.which === 39) {
    newPosition = `box-${currentPos + 1}`;
    naviCtrl.removeCharacter(DOMstrings);
    naviCtrl.rightBtn(currentPos, chosenCharacter, newPosition);
  }
});

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

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