首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在javascript中获取组合键的键码?

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

Stack Overflow用户
提问于 2013-01-31 17:15:45
回答 3查看 793关注 0票数 1
代码语言:javascript
复制
    $(document).keydown(function(event) {

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

有了上面的代码,我就可以得到单键的键码。但是,当我使用组合键时,我得到了第一个和第二个键的事件。例如,!(Shift + 1)、$(Shift + 4)。

如何获取组合键的键码?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-01-31 17:27:54

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

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

Stack Overflow用户

发布于 2013-01-31 17:45:22

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

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

代码语言:javascript
复制
  $.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时会触发此操作

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

下面是一个关于JSBin的工作示例

编辑备注。修复了验证结果为true时按键连续触发的问题

Edit2:修复了last变量,未正确使用...

票数 1
EN

Stack Overflow用户

发布于 2013-01-31 17:23:21

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

代码语言:javascript
复制
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];
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14622117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档