我正在尝试同时使用 click 和 keydown,但在按键时遇到了问题。如果我们可以在一个语句中加入这两个事件,是否有可能。
HTML
<audio id="Q" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"> </audio>
<div>
<button name="Q">Q</button>
</div>
JavaScript
const queButton = document.querySelector("[name=Q]");
queButton.addEventListener("click", function() {
document.getElementById("Q").play();
});
queButton.addEventListener("keydown", function(e) {
if (e.key == 81) {
document.getElementById("Q").play();
}
});
最佳答案
因为音频播放仅在按下特定键时发生,所以不可能在 click
和 keydown
事件之间共享整个事件处理程序。
但是可以定义一个可重复使用的函数(即 playSoundQ()
),如下所示:
/* Define reusable play sound function for both events */
function playSoundQ() {
document.getElementById("Q").play();
}
const qButton = document.querySelector("[name=Q]");
/* It's possible to pass the playSoundQ directly as the event handler
here, seeing there's no additional logic in the event handler */
qButton.addEventListener("click", playSoundQ);
/* Add keydown event listener to document rather than button */
document.addEventListener("keydown", function(e) {
/* Change to keyCode */
if (e.keyCode == 81) {
playSoundQ();
}
});
<audio id="Q" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>
<div>
<button name="Q">Q</button>
</div>
另请注意,此处应用了一些修复; keydown
监听器被添加到 document
而不是 button
以确保基于键的播放响应浏览器中发生的所有键事件。 keydown
处理程序中的 e.key
也已更正为 e.keyCode
以确保在按下“Q”键时进行播放.
希望对您有所帮助!
关于javascript - 我们如何在 javascript 中添加两个事件监听器 click 和 keydown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127282/