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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2511388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:41:23  来源:igfitidea点击:

How can I add a JavaScript keyboard shortcut to an existing JavaScript Function?

javascriptscriptingkeyboardshortcut

提问by Chris

Here is my code:

这是我的代码:

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?

我想为此代码添加一个键盘快捷键,我该怎么做才能在单击按钮时也可以执行该功能?

Tried to add an else if statement but it doesn't work, any ideas?

试图添加一个 else if 语句,但它不起作用,有什么想法吗?

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

    else if (e.ctrlKey && e.keyCode == 84) {
        playSound();
    }
}

回答by lincolnk

an event handler for the document's keyup event seems like an appropriate solution

文档 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);

回答by mr.mii

If you are only searching for trigger an event after pressing a key, try this:

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

In this example press 'ALT + a'

在这个例子中按'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;
  }
}

Here is a fiddle: https://jsfiddle.net/dmtf6n27/38/

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

Please also note there is a difference for the keycode numbers, whether you are using onkeypressor onkeyup. More info here: w3 schools KeyboardEvent keyCode Property

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

回答by Sikha

//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. ......

回答by xr280xr

These appear to all be using the deprecated keyCodeand whichproperties. Here is a non-deprecated version using jQuery to wire up the event:

这些似乎都在使用 deprecatedkeyCodewhich属性。这是一个使用 jQuery 连接事件的非弃用版本:

$("body").on("keyup", function (e) {
    if(e.ctrlKey && e.key == 'x')
        pauseSound();
    else if(e.ctrlKey && e.key == 't')
        playSound();
})

Note: ctrl + t may already be assigned to opening a new browser tab

注意: ctrl + t 可能已经被分配到打开一个新的浏览器选项卡

回答by Wesos de Queso

This worked for me

这对我有用

document.onkeyup=function(e){
  var e = e || window.event;
  if(e.which == 37) {
    $("#prev").click()
  }else if(e.which == 39){
    $("#next").click()
  }
}

回答by s15199d

Catch the key code and then call your function. This example catches the ESCkey and calls your function:

捕获关键代码,然后调用您的函数。此示例捕获ESC键并调用您的函数:

function getKey(key) {
    if ( key == null ) {
        keycode = event.keyCode;
    // To Mozilla
    } else {
        keycode = key.keyCode;
    }
    // Return the key in lower case form    
    if (keycode ==27){
        //alert(keycode);
        pauseSound();
        return false;
    }
    //return String.fromCharCode(keycode).toLowerCase();
}
$(document).ready( function (){
    $(document).keydown(function (eventObj){
        //alert("Keydown: The key is: "+getKey(eventObj));
        getKey(eventObj);
    });
});

You'll need JQUERYfor this example.

在这个例子中你需要JQUERY

回答by npup

Here's some stuff to use if you want. You can register a bunch of keys and handler with it.

如果你愿意,这里有一些东西可以使用。您可以使用它注册一堆密钥和处理程序。

Comments are in the code, but i short it goes like this:
It sets up a listener on the documentand manages a hash with the key combinations for which you want to listen.
* When you register a key (combination) to listen for, you submit the keycode (preferrably as a constant taken from the exported "key" property, to which you can add more constants for yourself), a handler function and possibly an options hash where you say if the ctrl and/or alt key are involved in your plans for this key.
* When you de-register a key (combination) you just submit the key and the optional hash for ctrl/alt-ness.

注释在代码中,但我简短地说它是这样的:
它在 上设置了一个侦听器,document并使用您想要侦听的组合键来管理一个散列。
* 当您注册要侦听的密钥(组合)时,您提交密钥代码(最好是从导出的“密钥”属性中获取的常量,您可以为自己添加更多常量)、处理程序函数和可能的选项哈希在这里您说 ctrl 和/或 alt 键是否涉及您对该键的计划。
* 当您注销一个密钥(组合)时,您只需提交密钥和可选的 ctrl/alt-ness 哈希。

window.npup = (function keypressListener() {
    // Object to hold keyCode/handler mappings
    var mappings = {};
    // Default options for additional meta keys
    var defaultOptions = {ctrl:false, alt:false};
    // Flag for if we're running checks or not
    var active = false;

    // The function that gets called on keyup.
    // Tries to find a handler to execute
    function driver(event) {
        var keyCode = event.keyCode, ctrl = !!event.ctrlKey, alt = !!event.altKey;
        var key = buildKey(keyCode, ctrl, alt);
        var handler = mappings[key];
        if (handler) {handler(event);}
    }

    // Take the three props and make a string to use as key in the hash
    function buildKey(keyCode, ctrl, alt) {return (keyCode+'_'+ctrl+'_'+alt);}

    function listen(keyCode, handler, options) {
        // Build default options if there are none submitted
        options = options || defaultOptions;
        if (typeof handler!=='function') {throw new Error('Submit a handler for keyCode #'+keyCode+'(ctrl:'+!!options.ctrl+', alt:'+options.alt+')');}
        // Build a key and map handler for the key combination
        var key = buildKey(keyCode, !!options.ctrl, !!options.alt);
        mappings[key] = handler;
    }

    function unListen(keyCode, options) {
        // Build default options if there are none submitted
        options = options || defaultOptions;
        // Build a key and map handler for the key combination
        var key = buildKey(keyCode, !!options.ctrl, !!options.alt);
        // Delete what was found
        delete mappings[key];
    }

    // Rudimentary attempt att cross-browser-ness
    var xb = {
        addEventListener: function (element, eventName, handler) {
            if (element.attachEvent) {element.attachEvent('on'+eventName, handler);}
            else {element.addEventListener(eventName, handler, false);}
        }
        , removeEventListener: function (element, eventName, handler) {
            if (element.attachEvent) {element.detachEvent('on'+eventName, handler);}
            else {element.removeEventListener(eventName, handler, false);}
        }
    };

    function setActive(activate) {
        activate = (typeof activate==='undefined' || !!activate); // true is default
        if (activate===active) {return;} // already in the desired state, do nothing
        var addOrRemove = activate ? 'addEventListener' : 'removeEventListener';
        xb[addOrRemove](document, 'keyup', driver);
        active = activate;
    }

    // Activate on load
    setActive();

    // export API
    return {
        // Add/replace handler for a keycode.
        // Submit keycode, handler function and an optional hash with booleans for properties 'ctrl' and 'alt'
        listen: listen
        // Remove handler for a keycode
        // Submit keycode and an optional hash with booleans for properties 'ctrl' and 'alt'
        , unListen: unListen
        // Turn on or off the whole thing.
        // Submit a boolean. No arg means true
        , setActive: setActive
        // Keycode constants, fill in your own here
        , key : {
            VK_F1 : 112
            , VK_F2: 113
            , VK_A: 65
            , VK_B: 66
            , VK_C: 67
        }
    };
})();

// Small demo of listen and unListen
// Usage:
//   listen(key, handler [,options])
//   unListen(key, [,options])
npup.listen(npup.key.VK_F1, function (event) {
    console.log('F1, adding listener on \'B\'');
    npup.listen(npup.key.VK_B, function (event) {
        console.log('B');
    });
});
npup.listen(npup.key.VK_F2, function (event) {
    console.log('F2, removing listener on \'B\'');
    npup.unListen(npup.key.VK_B);
});
npup.listen(npup.key.VK_A, function (event) {
    console.log('ctrl-A');
}, {ctrl: true});
npup.listen(npup.key.VK_A, function (event) {
    console.log('ctrl-alt-A');
}, {ctrl: true, alt: true});
npup.listen(npup.key.VK_C, function (event) {
    console.log('ctrl-alt-C => It all ends!');
    npup.setActive(false);
}, {ctrl: true, alt: true});

It is not terribly tested, but seemed to work OK.

它没有经过严格的测试,但似乎工作正常。

Look at http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspxto find a lot of keyCodes to use,

http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx,找到很多keyCodes使用,

回答by www139

Solution:

解决方案:

var activeKeys = [];

//determine operating system
var os = false;
window.addEventListener('load', function() {
  var userAgent = navigator.appVersion;
  if (userAgent.indexOf("Win") != -1) os = "windows";
  if (userAgent.indexOf("Mac") != -1) os = "osx";
  if (userAgent.indexOf("X11") != -1) os = "unix";
  if (userAgent.indexOf("Linux") != -1) os = "linux";
});

window.addEventListener('keydown', function(e) {
  if (activeKeys.indexOf(e.which) == -1) {
    activeKeys.push(e.which);
  }

  if (os == 'osx') {

  } else {
    //use indexOf function to check for keys being pressed IE
    if (activeKeys.indexOf(17) != -1 && activeKeys.indexOf(86) != -1) {
      console.log('you are trying to paste with control+v keys');
    }
    /*
      the control and v keys (for paste)
      if(activeKeys.indexOf(17) != -1 && activeKeys.indexOf(86) != -1){
        command and v keys are being pressed
      }
    */
  }
});

window.addEventListener('keyup', function(e) {
  var result = activeKeys.indexOf(e.which);
  if (result != -1) {
    activeKeys.splice(result, 1);
  }
});

Explanation: I ran into this same problem and came up with my own solution. e.metaKeydidn't seem to work with the keyup event in Chrome and Safari. However, I'm not sure if it was specific to my application since I had other algorithms blocking some key events and I may have mistakenly blocked the meta key.

说明:我遇到了同样的问题,并提出了自己的解决方案。e.metaKey似乎不适用于 Chrome 和 Safari 中的 keyup 事件。但是,我不确定它是否特定于我的应用程序,因为我有其他算法阻止了一些关键事件,而且我可能错误地阻止了元密钥。

This algorithm monitors for keys going down and then adds them to a list of keys that are currently being pressed. When released, the key is removed from the list. Check for simultaneous keys in the list by using indexOfto find key codes in the array.

该算法会监视按下的键,然后将它们添加到当前正在按下的键列表中。释放后,密钥将从列表中删除。通过使用indexOf查找数组中的键代码来检查列表中的同时键。