【问题标题】:How do I make the multiple keydown event work without breaking?如何在不中断的情况下使多个 keydown 事件工作?
【发布时间】:2019-10-10 23:20:45
【问题描述】:
    $(document).on('keydown', function(event) {
            const current = audios[Number(event.key) // audios is array of music files
            current.currentTime = 0;
            current.play();
    });

我正在创建一个鼓应用程序。如果我用 keydown 事件按下数字 2,它将被激活。当我按住数字 2 并按 3 时,数字 2 将停止发声。我怎样才能让它发生?为什么不这样做呢?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您的代码中似乎存在语法错误。 const current = audios[Number(event.key) 缺少结束 ]

这是我的处理方法。

const pressedKeys = {};

$(document.body).keydown(function (evt) {
  pressedKeys[Number(evt.key)] = true;
  playSongs(pressedKeys);
});

$(document.body).keyup(function (evt) {
  pressedKeys[Number(evt.key)] = false;
});

function playSongs(dict) {
  for (let song in dict) {
    if (dict[song] === true) {
      audios[song].currentTime = 0;
      audios[song].play();
    }
  }
}

此代码跟踪字典中的键。每当注册 keydown 时,它就会将其添加到字典中。紧接着,playSongs 找到所有正确的键并播放该歌曲。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2021-04-06
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多