【问题标题】:How can I add a JavaScript keyboard shortcut to an existing JavaScript Function?如何将 JavaScript 键盘快捷键添加到现有 JavaScript 函数?
【发布时间】:2011-01-31 11:14:47
【问题描述】:

这是我的代码:

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();
    }
}

【问题讨论】:

  • else-if 的实际语法是 else if () { }。删除连字符。

标签: javascript scripting keyboard shortcut


【解决方案1】:

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

【讨论】:

  • 这很好用,谢谢。我怎么能两次使用这个代码,因为我需要另一个快捷键'playSound()'?
  • 添加类似于第一个 if 语句的 else-if 语句,但根据需要更改键码。从那里拨打你的 playSound() 电话。如果您想对两个活动使用相同的键,则必须设置一个标志变量并在按下键时检查/设置它以确定要执行的操作。
  • 那些不支持addEventListener的浏览器呢?
  • IE 是我用过的唯一一个没有的,你可以使用 document.attachEvent('onkeyup', doc_keyUp);应该有很多关于在调用函数之前检查函数是否存在的参考。
  • 我尝试添加了一个else-if,但是不起作用,请参考主题帖子查看更新后的代码。
【解决方案2】:

如果你想在按键后触发事件,试试:

在本例中按 ALT+a

document.onkeyup=functione{
  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;
  }
}

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

还请注意,无论您使用的是onkeypress 还是onkeyup,键码编号都存在差异。 W3 Schools' "KeyboardEvent keyCode" Property 有更多信息。

【讨论】:

    【解决方案3】:
    //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. ......
    

    【讨论】:

      【解决方案4】:

      这是我的解决方案:

      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!")
      })
      
      • 当你调用我的函数时,它会创建一个名为currentKeys的数组;这些是当时将被按住的键。
      • 每次按下某个键时,由于onkeydown 而感应到,它就会被添加到currentKeys 数组中。
      • 当按键被释放时,由于onkeyup 而感应到,阵列被重置,这意味着此时没有按键被按下。
      • 每次它都会检查快捷方式是否匹配。如果是,它将调用处理程序。

      【讨论】:

        【解决方案5】:

        这对我有用

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

        【讨论】:

        • 我尝试使用onkeyup,但它一键运行了 18 次。改用onkeydown,它只运行一次。
        【解决方案6】:

        获取关键代码,然后调用您的函数。此示例捕获 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);
            });
        });
        

        此示例需要 JQUERY

        【讨论】:

          【解决方案7】:

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

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

          注意:Ctrl+t 可能已经分配给打开一个新的浏览器选项卡。

          【讨论】:

          【解决方案8】:

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

          注释在代码中,但简而言之,它在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});
          

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

          Javascript Char Codes (Key Codes)发现好多keyCodes可以用,

          【讨论】:

            【解决方案9】:

            解决方案:

            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);
              }
            });

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

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

            【讨论】:

              【解决方案10】:

              在 React 中使用 ctrl+s 保存

              useEffect(() => {
                      document.onkeydown = function (e) {
                          if (e.ctrlKey == true && e.key == 's') {
                              e.preventDefault() // to override browser's default save page feature
                              alert('ctrl+s is working for save!') // invoke your API to save
                          }
                      }
              }, [])
              

              【讨论】:

                猜你喜欢
                • 2014-05-29
                • 2020-12-26
                • 2016-12-02
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多