如何通过JavaScript检测键盘修改器(Ctrl或Shift)

时间:2012-11-24 08:08:45

标签: javascript

我有一个检测最大长度的功能。但问题是当最大长度达到Ctrl + A组合时不起作用。如何通过javascript检测Ctrl + A组合。

这是我的maxlength代码。

if (event.keyCode==8 || event.keyCode==9 || event.keyCode==37 || event.keyCode==39 ){
        return true;
} else {            
        if((t.length)>=50) {    
            return false;
        }   
}

5 个答案:

答案 0 :(得分:23)

检查event.ctrlKey

function keyHandler(event) {
    event = event || window.event;
    if(event.keyCode==65 && event.ctrlKey) {
        // ctrl+a was typed.
    }
}

答案 1 :(得分:3)

密码:

shift   16
ctrl    17
alt     18

你的jQuery:

$(document).keydown(function (e) {
    if (e.keyCode == 18) {
        alert("ALT was pressed");
    }
});

JavaScript Madness: Keyboard Events

答案 2 :(得分:1)

您可以使用以下内容:

document.onkeypress = function(evt) {
  evt = evt || window.event;
  etv = evt;
  switch (etv.keyCode) {
    case 16:
      // Code to do when Shift presed
      console.log('Pressed [SHIFT]');
      break;
    case 17:
      // Code to do when CTRL presed
      console.log('Pressed [CTRL]');
      break;
    case 32:
      // Code to do when ALT presed
      console.log('Pressed [ALT]');
      break;
  }
};

答案 3 :(得分:0)

我也需要一个解决方案,所以发现一些有用的东西,清理它们的代码要少得多,ES6 ...... JSFiddle link

function isCapsLock(event=window.event) {
  const code = event.charCode || event.keyCode;

  if (code > 64 && code < 91 && !event.shiftKey) {
    return true;
  }

  return false;
}

document.getElementById("text").addEventListener("keypress", event => {
  const status = document.getElementById("status");
  if (isCapsLock(event)) {
    status.innerHTML = "CapsLocks enabled";
    status.style.color = "red";
  } else {
    status.innerHTML = "CapsLocks disabled";
    status.style.color = "blue";
  }
}, false);
<input type="text" id="text" /><br>
<span id="status"></span>

答案 4 :(得分:0)

这是一个非常老的问题。只有当我们手头有一个作为函数参数传递的KeyboardEvent类型的事件对象时,gilly3的答案才有效。如果我们没有 event 对象(例如此功能)可用,如何检测当前的控制键状态?

function testModifierKey() {
  // have I some modifier key hold down at this running time?
}

我从https://gist.github.com/spikebrehm/3747378的Spirkbrehm中进行了长时间搜索后,找到了解决方案。他的解决方案是随时使用带有全局变量的jQuery跟踪修饰键状态。

全局变量 window.modifierKey 可以在任何情况下使用,而无需 event 对象。

function testModifierKey() {
  // have I have some modifier key hold down at this executing time?
  if(window.modifierKey) {
    console.log("Some modifier key among shift, ctrl, alt key is currently down.");
    // do something at this condition... for example, delete item without confirmation.
  } else {
    console.log("No modifier key is currently down.");
    // do something at other condition... for example, delete this item from shopping cart with confirmation.
  }
}

这是要在您的HTML文档中加载的脚本:

// source: https://gist.github.com/spikebrehm/3747378
// modifierKey used to check if cmd+click, shift+click, etc. 
!function($, global){
  var $doc = $(document);
  var keys;

  global.modifierKey = false;

   global.keys = keys = {
      'UP': 38,
      'DOWN': 40,
      'LEFT': 37,
      'RIGHT': 39,
      'RETURN': 13,
      'ESCAPE': 27,
      'BACKSPACE': 8,
      'SPACE': 32
  };

  // borrowed from Galleria.js
  var keyboard = {
    map: {},
    bound: false,

    press: function(e) {
      var key = e.keyCode || e.which;
      if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) {
        keyboard.map[key].call(self, e);
      }
    },

    attach: function(map){
      var key, up;

      for(key in map) {
        if (map.hasOwnProperty(key)) {
          up = key.toUpperCase();
          if (up in keyboard.keys) {
            keyboard.map[keyboard.keys[up]] = map[key];
          } else {
            keyboard.map[up] = map[key];
          }
        }
      }
      if (!keyboard.bound) {
        keyboard.bound = true;
        $doc.bind('keydown', keyboard.press);
      }
    },

    detach: function() {
      keyboard.bound = false;
      keyboard.map = {};
      $doc.unbind('keydown', keyboard.press);
    }
  };

  $doc.keydown(function(e) {
    var key = e.keyCode || e.which;
    if (key === 16 || key === 91 || key === 18 || key === 17) {
      modifierKey = true;
    } else {
      modifierKey = false;
    }
  });

  $doc.keyup(function(e) {
    modifierKey = false;
  });
}(jQuery, window);