本文介紹了如何將 JavaScript 鍵盤快捷鍵添加到現有 JavaScript 函數?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
這是我的代碼:
function pauseSound() {
var pauseSound = document.getElementById("backgroundMusic");
pauseSound.pause();
}
我想為這段代碼添加一個鍵盤快捷鍵,我該如何做,以便在單擊按鈕時也可以執行該功能?
I would like to add a keyboard shortcut to this code, how can I do this so that the function can also be executed when a button is clicked too?
嘗試添加一個 else if 語句,但它不起作用,有什么想法嗎?
Tried to add an else if statement but it doesn't work, any ideas?
function doc_keyUp(e) {
if (e.ctrlKey && e.keyCode == 88) {
pauseSound();
}
else if (e.ctrlKey && e.keyCode == 84) {
playSound();
}
}
推薦答案
文檔的 keyup 事件的事件處理程序似乎是一個合適的解決方案.
An event handler for the document's keyup event seems like an appropriate solution.
注意:KeyboardEvent.keyCode
已被棄用,取而代之的是 key
.
Note: KeyboardEvent.keyCode
was deprecated in favor of 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 函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!