这是我的代码:
function pauseSound() {
var pauseSound = document.getElementById("backgroundMusic");
pauseSound.pause();
}
我想为这段代码添加一个键盘快捷键,我该怎么做才能在单击按钮时也执行该功能?
尝试添加一个 else if 语句但它不起作用,有什么想法吗?
function doc_keyUp(e) {
if (e.ctrlKey && e.keyCode == 88) {
pauseSound();
}
else if (e.ctrlKey && e.keyCode == 84) {
playSound();
}
}
最佳答案
文档的 keyup 事件的事件处理程序似乎是一个合适的解决方案。
注意:KeyboardEvent.keyCode
已弃用,取而代之的是 key
。
// define a handler
function doc_keyUp(e) {
// this would test for whichever key is 40 (down arrow) and the ctrl key at the same time
if (e.ctrlKey && e.key === 'ArrowDown') {
// call your function to do the thing
pauseSound();
}
}
// register the handler
document.addEventListener('keyup', doc_keyUp, false);
关于javascript - 如何向现有的 JavaScript 函数添加键盘快捷键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2511388/