Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jQuery/JavaScript进行键组合_Javascript_Jquery_Plugins_Keyboard Shortcuts_Jkey - Fatal编程技术网

使用jQuery/JavaScript进行键组合

使用jQuery/JavaScript进行键组合,javascript,jquery,plugins,keyboard-shortcuts,jkey,Javascript,Jquery,Plugins,Keyboard Shortcuts,Jkey,我很好奇,在这个问题的底部,我写了下面的jQuery插件代码,如何实现键组合。到目前为止,它的工作原理是,它允许用户通过执行普通的类似jQuery的语法来创建键命令,并为键命令提供一个事件,如下所示: $(window).jkey('a',function(){ alert('you pressed the a key!'); }); 或 最后,我想要的是做事情的能力,但我想不出: $(window).jkey('alt+n',function(){ alert('you pres

我很好奇,在这个问题的底部,我写了下面的jQuery插件代码,如何实现键组合。到目前为止,它的工作原理是,它允许用户通过执行普通的类似jQuery的语法来创建键命令,并为键命令提供一个事件,如下所示:

$(window).jkey('a',function(){
   alert('you pressed the a key!');
});

最后,我想要的是做事情的能力,但我想不出:

$(window).jkey('alt+n',function(){
   alert('you pressed alt+n!');
});
我知道如何在插件之外做这件事(上键设置var false,下键设置var true,当你按下另一个键时检查var是否为真),但我不知道当你不知道要按下什么键和多少键时如何做。如何添加此支持?如果他们愿意,我希望能够允许他们做
alt+shift+a
a+s+d+f
。我就是不知道该如何实施。有什么想法吗

我将把它作为一个开源插件发布,我很乐意在博客文章和代码中给任何给我权利、工作、回答的人一些信任。提前谢谢

(function($) {
  $.fn.jkey = function(keyCombo,callback) {
    if(keyCombo.indexOf(' ') > -1){ //If multiple keys are selected
        var keySplit = keyCombo.split(' ');
    }
    else{ //Else just store this single key
        var keySplit = [keyCombo];
    }
    for(x in keySplit){ //For each key in the array...

        if(keySplit[x].indexOf('+') > -1){
            //Key selection by user is a key combo... what now?
        }
        else{
            //Otherwise, it's just a normal, single key command
        }

        switch(keySplit[x]){
            case 'a':
                keySplit[x] = 65;
                break;
            case 'b':
                keySplit[x] = 66;
                break;
            case 'c':
                keySplit[x] = 67;
                break;
            //And so on for all the rest of the keys
        }
    }
    return this.each(function() {
        $this = $(this);
        $this.keydown(function(e){
            if($.inArray(e.keyCode, keySplit) > -1){ //If the key the user pressed is matched with any key the developer set a key code with...
                if(typeof callback == 'function'){ //and they provided a callback function
                    callback(); //trigger call back and...
                    e.preventDefault(); //cancel the normal
                }
            }
        });
    });
  }
})(jQuery);

这只是在黑暗中拍摄,但可能会帮助你走上正确的道路


如果可以让该函数识别您输入的键的十六进制值,而不是文字键(例如字母“n”的0x6E),则可以派生“alt+n”转换为十六进制,并让函数查找该值。

使用keypress而不是keyup/keydown,因为后两种方法不能准确地显示键码(,请参见最后一段)。在这种情况下,您可以引用事件对象的
altKey
ctrlKey
shiftKey
布尔属性

$(document).keypress(function(e) {
  var key = String.fromCharCode(e.which);
  var alt = e.altKey;
  var ctrl = e.ctrlKey
  var shift = e.shiftKey;
  alert("Key:" + key + "\nAlt:" + alt + "\nCtrl:" + ctrl + "\nShift:" + shift);
});
此外,您还可以使用
String.fromCharCode
将关键代码转换为实际字母

除了使用Ctrl、Alt和Shift组合键外,不能捕获多个键。你根本不可能在一个事件中做到这一点。所以把
a+s+d+f
的想法扔出窗外

注意:显然,浏览器使用某些组合键。例如,Alt+F通常会在Windows中打开“文件”菜单。Ctrl+N通常会启动一个新窗口/选项卡。不要试图覆盖这些组合中的任何组合


这是一个让您感到测试愉快的方法。

这是我的想法。基本上,我所做的是创建一个JSON对象来存储所有关键代码。然后,我用代码替换所有提供的钥匙。若这些键使用“+”来创建一个键组合,那个么我就用它创建一个代码数组

然后,我们创建另一个数组来存储所有被按下的键(keyDown添加该项,keydup删除该项)。在keyDown上,我们检查它是单键命令还是组合键。如果它是一个组合,我们将根据所有当前活动的按键来检查它。如果它们都匹配,我们执行回调

这将适用于任意数量的键组合。我唯一一次看到它不起作用的是当您使用“alert()”在按键组合上显示消息时,因为它将不再从活动按键阵列中删除项目

(function($) { 
  $.fn.jkey = function(keyCombo,callback) {

    // Save the key codes to JSON object
    var keyCodes = { 
      'a'   : 65,
      'b'   : 66,
      'c'   : 67,
      'alt' : 18
    };

    var x = '';
    var y = '';

    if(keyCombo.indexOf(' ') > -1){ //If multiple keys are selected
        var keySplit = keyCombo.split(' ');
    }
    else{ //Else just store this single key
        var keySplit = [keyCombo];
    }

    for(x in keySplit){ //For each key in the array...

      if(keySplit[x].indexOf('+') > -1){
        //Key selection by user is a key combo
        // Create a combo array and split the key combo
        var combo = Array();
        var comboSplit = keySplit[x].split('+');

        // Save the key codes for each element in the key combo
        for(y in comboSplit){
          combo[y] = keyCodes[ comboSplit[y] ];
        }

        keySplit[x] = combo;

      } else {
        //Otherwise, it's just a normal, single key command
        keySplit[x] = keyCodes[ keySplit[x] ];
      }

    }

    return this.each(function() {
        $this = $(this);

        // Create active keys array
        // This array will store all the keys that are currently being pressed
        var activeKeys = Array();

        $this.keydown(function(e){

          // Save the current key press
          activeKeys[ e.keyCode ] = e.keyCode;

          if($.inArray(e.keyCode, keySplit) > -1){ // If the key the user pressed is matched with any key the developer set a key code with...

            if(typeof callback == 'function'){ //and they provided a callback function
              callback(); //trigger call back and...
              e.preventDefault(); //cancel the normal
            }

          } else { // Else, the key did  not match which means it's either a key combo or just dosn't exist

            // Check if the individual items in the key combo match what was pressed
            for(x in keySplit){
              if($.inArray(e.keyCode, keySplit[x]) > -1){

                // Initiate the active variable
                var active = 'unchecked';

                // All the individual keys in the combo with the keys that are currently being pressed
                for(y in keySplit[x]) {
                  if(active != false) {
                    if($.inArray(keySplit[x][y], activeKeys) > -1){
                      active = true;
                    } else {
                      active = false;
                    }
                  }
                }

                // If all the keys in the combo are being pressed, active will equal true
                if(active === true){
                  if(typeof callback == 'function'){ //and they provided a callback function
                    callback(); //trigger call back and...
                    e.preventDefault(); //cancel the normal
                  }
                }
              }
            }

          } // end of if in array

        }).keyup(function(e) {
          // Remove the current key press
          activeKeys[ e.keyCode ] = '';
        });

    });

  }
})(jQuery);

如果您正在寻找一种可以让用户使用普通输入框轻松输入和定义按键组合的工具,我为您编写了一个插件:

Awh,有趣,我会研究它。谢谢另外,您是否有关于如何通过JS转换它们的参考资料?我还没有用谷歌搜索过……那么我该如何整合它呢?我该如何整合它,以便任何组合键都能正常工作,例如shift+alt+f+d+s,如果他们愿意的话。就像我说的,这是给我的,但它也将公开发布,所以我仍然需要允许then覆盖浏览器默认值,如ctrl+t,尽管我从来不会:)哦,那么,shift+alt+f呢,我如何将其集成到插件中,对不起,你不能捕获多个键,所以忘了它吧。每次按键都会触发一次事件。布尔指示器只告诉您在按下键时是否按住了Ctrl、Alt或Shift键。就覆盖浏览器默认值而言,否、否和否@Oscar回应您的第二条评论:
if(key==“F”&&alt&&shift){alert(“OK!”);}
@Oscar和shift+alt+F甚至可能不起作用,因为浏览器可能已经为alt+F连接了一些东西。您正在全局范围中定义
x
。我认为可以通过如下定义x和y来解决范围问题:var x='';变量y=“”?或者更好的是,我们可以通过在for语句中添加var来定义它们?对于(键分裂中的变量x){。。。
(function($) { 
  $.fn.jkey = function(keyCombo,callback) {

    // Save the key codes to JSON object
    var keyCodes = { 
      'a'   : 65,
      'b'   : 66,
      'c'   : 67,
      'alt' : 18
    };

    var x = '';
    var y = '';

    if(keyCombo.indexOf(' ') > -1){ //If multiple keys are selected
        var keySplit = keyCombo.split(' ');
    }
    else{ //Else just store this single key
        var keySplit = [keyCombo];
    }

    for(x in keySplit){ //For each key in the array...

      if(keySplit[x].indexOf('+') > -1){
        //Key selection by user is a key combo
        // Create a combo array and split the key combo
        var combo = Array();
        var comboSplit = keySplit[x].split('+');

        // Save the key codes for each element in the key combo
        for(y in comboSplit){
          combo[y] = keyCodes[ comboSplit[y] ];
        }

        keySplit[x] = combo;

      } else {
        //Otherwise, it's just a normal, single key command
        keySplit[x] = keyCodes[ keySplit[x] ];
      }

    }

    return this.each(function() {
        $this = $(this);

        // Create active keys array
        // This array will store all the keys that are currently being pressed
        var activeKeys = Array();

        $this.keydown(function(e){

          // Save the current key press
          activeKeys[ e.keyCode ] = e.keyCode;

          if($.inArray(e.keyCode, keySplit) > -1){ // If the key the user pressed is matched with any key the developer set a key code with...

            if(typeof callback == 'function'){ //and they provided a callback function
              callback(); //trigger call back and...
              e.preventDefault(); //cancel the normal
            }

          } else { // Else, the key did  not match which means it's either a key combo or just dosn't exist

            // Check if the individual items in the key combo match what was pressed
            for(x in keySplit){
              if($.inArray(e.keyCode, keySplit[x]) > -1){

                // Initiate the active variable
                var active = 'unchecked';

                // All the individual keys in the combo with the keys that are currently being pressed
                for(y in keySplit[x]) {
                  if(active != false) {
                    if($.inArray(keySplit[x][y], activeKeys) > -1){
                      active = true;
                    } else {
                      active = false;
                    }
                  }
                }

                // If all the keys in the combo are being pressed, active will equal true
                if(active === true){
                  if(typeof callback == 'function'){ //and they provided a callback function
                    callback(); //trigger call back and...
                    e.preventDefault(); //cancel the normal
                  }
                }
              }
            }

          } // end of if in array

        }).keyup(function(e) {
          // Remove the current key press
          activeKeys[ e.keyCode ] = '';
        });

    });

  }
})(jQuery);