如何向现有JavaScript函数添加JavaScript键盘快捷键?

Chr*_*ris 45 javascript keyboard scripting shortcut

这是我的代码:

function pauseSound() {
    var pauseSound = document.getElementById("backgroundMusic");
    pauseSound.pause(); 
}
Run Code Online (Sandbox Code Playgroud)

我想为这段代码添加一个键盘快捷键,我怎么能这样做才能在单击按钮时执行该功能呢?

试图添加一个else if语句,但它不起作用,任何想法?

function doc_keyUp(e) {
    if (e.ctrlKey && e.keyCode == 88) {
        pauseSound();
    }

    else if (e.ctrlKey && e.keyCode == 84) {
        playSound();
    }
}
Run Code Online (Sandbox Code Playgroud)

lin*_*lnk 70

文档的keyup事件的事件处理程序似乎是一个合适的解决方案

// define a handler
function doc_keyUp(e) {

    // this would test for whichever key is 40 and the ctrl key at the same time
    if (e.ctrlKey && e.keyCode == 40) {
        // call your function to do the thing
        pauseSound();
    }
}
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);
Run Code Online (Sandbox Code Playgroud)


mr.*_*mii 6

如果您只是在按下按键后搜索触发事件,请尝试以下操作:

在这个例子中按'ALT + a'

document.onkeyup=function(e){
  var e = e || window.event; // for IE to cover IEs window event-object
  if(e.altKey && e.which == 65) {
    alert('Keyboard shortcut working!');
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个小提琴:https : //jsfiddle.net/dmtf6n27/38/

另请注意,无论您使用的是onkeypress还是onkeyup,键码编号都存在差异。更多信息:w3 school KeyboardEvent keyCode 属性


小智 5

//For single key: Short cut key for 'Z'
document.onkeypress = function (e) {
    var evt = window.event || e;
    switch (evt.keyCode) {
        case 90:  
            // Call your method Here
            break;
    }
}

//For combine keys like Alt+P
document.onkeyup = function (e) {
    var evt = window.event || e;   
        if (evt.keyCode == 80 && evt.altKey) {
            // Call Your method here   
        }
    }
}
    //ensure if short cut keys are case sensitive.
    //    If its not case sensitive then
    //check with the evt.keyCode values for both upper case and lower case. ......
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我的解决方案:

HTMLElement.prototype.onshortcut = function(shortcut, handler) {
    var currentKeys = []
    
    function reset() {
        currentKeys = []
    }

    function shortcutMatches() {
        currentKeys.sort()
        shortcut.sort()

        return (
            JSON.stringify(currentKeys) ==
            JSON.stringify(shortcut)
        )
    }

    this.onkeydown = function(ev) {
        currentKeys.push(ev.key)

        if (shortcutMatches()) {
            ev.preventDefault()
            reset()
            handler(this)
        }

    }

    this.onkeyup = reset
}


document.body.onshortcut(["Control", "Shift", "P"], el => {
    alert("Hello!")
})
Run Code Online (Sandbox Code Playgroud)
  • 当您调用我的函数时,它将创建一个名为currentKeys;的数组。这些是当时按下的键。
  • 每次按下某个键时,都会将onkeydown其添加到currentKeys数组中。
  • 当按键被释放时,由于 被检测到onkeyup,阵列被重置,这意味着此时没有按键被按下。
  • 每次它都会检查快捷方式是否匹配。如果确实如此,它将调用处理程序。