如何检测 javascript 中的 shift + key down?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7479307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:26:28  来源:igfitidea点击:

How can I detect shift + key down in javascript?

javascript

提问by Bart

Possible Duplicate:
How to catch enter keypress on textarea but not shift+enter?

可能的重复:
如何在 textarea 上捕获输入键而不是 shift+enter?

How can I detect shift + key down in JavaScript?

如何在 JavaScript 中检测 shift + key down?

采纳答案by Adam Eberlin

var onkeydown = (function (ev) {
  var key;
  var isShift;
  if (window.event) {
    key = window.event.keyCode;
    isShift = !!window.event.shiftKey; // typecast to boolean
  } else {
    key = ev.which;
    isShift = !!ev.shiftKey;
  }
  if ( isShift ) {
    switch (key) {
      case 16: // ignore shift key
        break;
      default:
        alert(key);
        // do stuff here?
        break;
    }
  }
});

回答by Niet the Dark Absol

event.shiftKeyis a boolean. trueif the Shift key is being pressed, falseif not. altKeyand ctrlKeywork the same way.

event.shiftKey是一个布尔值。true如果正在按下 Shift 键,false如果没有。altKeyctrlKey以同样的方式工作。

So basically you just need to detect the keydown as normal with onkeydown, and check those properties as needed.

所以基本上你只需要像往常一样检测 keydown onkeydown,并根据需要检查这些属性。