如何在javascript中获取键组合键码?

时间:2013-01-31 09:15:45

标签: javascript

    $(document).keydown(function(event) {

        doSomething(event);
        event.preventDefault();
    });

使用上面的代码,我可以获得单个密钥的密钥代码。但是,当我使用密钥的组合时,我正在获得第一个和第二个密钥的事件。例如,!(Shift + 1),$(Shift + 4)。

如何获得键组合的键码?

3 个答案:

答案 0 :(得分:1)

以下是一些可以帮助您的插件:

  1. https://github.com/jeresig/jquery.hotkeys
  2. https://github.com/madrobby/keymaster(这个是免费的)

答案 1 :(得分:1)

你可以使用一个处理触发回调函数的函数扩展jquerys fn对象,基于按下的键和正则表达式匹配

我写了一个类似的Answer,之前支持单键的正则表达式匹配,我只是稍微修改它以支持多个键。

  $.fn.selectedKey = (function () {
      var keys = "";
      var last = "";
      var key = "";
      return function (cb, data) {
          def.call(data, {
              ctrlKey: 2, //0: musn't be pressed, 1: must be pressed, 2: both.
              altKey: 2, // "
              invert: 0, //inverts the filter
              filter: /.*/, // A Regular Expression, or a String with a Regular Expression
              preventDefault: false //Set to true to prevent Default.
          }); //Sets the default Data for the values used,

          function validate(e) {

              var exp = new RegExp(e.data.filter.replace(/\\\\(\d)/g, String.fromCharCode("$1"))); //Creates a new RegExp from a String to e.g. allow "\2" to match the keyCode 2
              var c = !! (e.data.ctrlKey ^ e.ctrlKey ^ 1 > 0); //c == true if the above stated conditions are met e.g Ctrl Key Pressed and `ctrlKey == 1` -> true
              var a = !! (e.data.altKey ^ e.altKey ^ 1 > 0); //e.g Alt Key Pressed and `altKey == 0` -> false
              //console.log(keys,exp,c,a)
              return (exp.test(keys) && (c && a)); //Returns the validation Result
          }

          function def(obj) { //a minimal helper for default values
              for (var prop in obj) {
                  this[prop] = this[prop] || obj[prop];
              }
          }
          this.keypress(data, function (e) {

              key = e.char = String.fromCharCode(e.keyCode || e.which); //Converts the pressed key to a String
              keys += ( !! ~ (keys.indexOf(key))) ? "" : key;
              key = key["to" + (e.shiftKey ? "Upper" : "Lower") + "Case"]();
              keys = keys["to" + (e.shiftKey ? "Upper" : "Lower") + "Case"](); //case handling
              if (e.data.preventDefault) e.preventDefault();

              if ((validate(e) != e.data.invert) && keys != last) {

                  cb(e);
                  last = keys;
                  //Calls the callback function if the conditions are met
              }
          });
          if (!this.data("keyupBound")) {
              this.keyup(data, function (e) {

                  key = e.char = String.fromCharCode(e.keyCode || e.which); //Converts 
                  var t = keys.toLowerCase()
                      .split("");
                  t.splice(t.indexOf(e.char), 1);
                  keys = t.join("");
                  last = keys;
              });
              this.data("keyupBound", true);
          }
      };

  })();


$("body").selectedKey(function (e) {
    console.log("All lower characters, Numbers and 'A': " + e.char);
}, {
    filter: "^[a-z]|[0-9]|A$",
    ctrlKey: 2,
    altKey: 2
});

$("body").selectedKey(function (e) {
    console.log("KeyCode 2 " + e.char); // Ctrl + b
}, {
    filter: "\\2",
    ctrlKey: 1,
    altKey: 2
});

你也可以做filter:/.{4,5}/,它会同时按下任意4到5个键

例如,当按下A + S + D时会触发

$("body").selectedKey(function (e) {
    console.log("ASD has been pressed"); // Ctrl + b
}, {
    filter: "^ASD$",
    ctrlKey: 2,
    altKey: 2
});

以下是JSBin

的一个实例

编辑注释。修复了如果验证评估为真,则在按住键时不断触发 Edit2:修复了last变量,未正确使用...

答案 2 :(得分:0)

你需要记住按下了哪个键。你应该听一下keyup + keydown事件:

var keyCodesPressed = {};

$(document).keydown(function(event) {
  keyCodesPressed[event.which] = true;
  // here you should have all keys which are currently pressed:
  for (keyCode in keyCodesPressed) {
    // and you can loop over them and detect which are the ones currently pressed
  } 
});

$(document).keyup(function(event) {
  delete keyCodesPressed[event.which];
});