Javascript 在“单击”事件上检查 Ctrl / Shift / Alt 键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2847135/
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-23 02:09:06  来源:igfitidea点击:

Check Ctrl / Shift / Alt keys on 'click' event

javascriptjqueryhtmlfirefox3.6

提问by Misha Moroshko

How could I identify whichCtrl/ Shift/ Altkeys are pressed in the following code ?

我怎么能确定哪个Ctrl/ Shift/Alt下面的代码键被按下?

$("#my_id").click(function() {
    if (<left control key is pressed>) { alert("Left Ctrl"); }
    if (<right shift and left alt keys are pressed>) { alert("Right Shift + Left Alt"); }
});

采纳答案by John Hartsock

Well you this wont work in all browsers just IE 8. Microsoft implemented the ability to determine which (right/left) key was pressed. Here is a link http://msdn.microsoft.com/en-us/library/ms534630(VS.85).aspx

好吧,这不适用于仅 IE 8 的所有浏览器。Microsoft 实现了确定按下哪个(右/左)键的功能。这是一个链接http://msdn.microsoft.com/en-us/library/ms534630(VS.85).aspx

I also found this wonder article about keypress, keyup, keydown event in browsers. http://unixpapa.com/js/key.html

我还发现了这篇关于浏览器中的 keypress、keyup、keydown 事件的精彩文章。 http://unixpapa.com/js/key.html

$('#someelement').bind('click', function(event){ 

    if(event.ctrlKey) {
      if (event.ctrlLeft) {
        console.log('ctrl-left'); 
      }
      else {
        console.log('ctrl-right');
      }
    }
    if(event.altKey) {
      if (event.altLeft) {
        console.log('alt-left'); 
      }
      else {
        console.log('alt-right');
      }
    }
    if(event.shiftKey) {
      if (event.shiftLeft) {
        console.log('shift-left'); 
      }
      else
      {
        console.log('shift-right');
      }
    }
  }); 

回答by jAndy

$('#someelement').bind('click', function(event){
   if(event.ctrlKey)
      console.log('ctrl');
   if(event.altKey)
      console.log('alt');
   if(event.shiftKey)
      console.log('shift');

});

I don't know if it's possible to check for left/right keys within a click event, but I don't think it's possible.

我不知道是否可以在单击事件中检查左/右键,但我认为这是不可能的。

回答by Ibrahim Khan

e.originalEvent.locationreturns 1 for left key and 2 for right key. Therefore you can detect which modifierkey is pressed like following. Hope this will help you.

e.originalEvent.location左键返回 1,右键返回 2。因此,您可以检测modifier按下了哪个键,如下所示。希望这会帮助你。

var msg = $('#msg');
$(document).keyup(function (e) {
      if (e.keyCode == 16) {
          if (e.originalEvent.location == 1)
              msg.html('Left SHIFT pressed.');
          else
              msg.html('Right SHIFT pressed.');
      } else if (e.keyCode == 17) {
          if (e.originalEvent.location == 1)
              msg.html('Left CTRL pressed.');
          else
              msg.html('Right CTRL pressed.');
      } else if (e.keyCode == 18) {
          if (e.originalEvent.location == 1)
              msg.html('Left ALT pressed.');
          else
              msg.html('Right ALT pressed.');
        
          e.preventDefault(); //because ALT focusout the element
      }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Press modifier key: </label>
<strong id="msg"></strong>

回答by DJHakim

In most instances the ALT, CTRL,and SHIFTkey booleans will work to see if those keys were pressed. For example:

在大多数情况下,ALT, CTRL, 和SHIFTkey 布尔值将用于查看是否按下了这些键。例如:

var altKeyPressed = instanceOfMouseEvent.altKey

When called upon, it will return true or false. For more info, go to https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey

当被调用时,它将返回 true 或 false。有关更多信息,请访问https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey

For future reference, there is also one called metaKey(NS/firefox only) which works when the meta key is pressed.

为了将来参考,还有一个称为metaKey(仅限 NS/firefox)的方法在按下元键时起作用。

回答by A. Wolff

Following my comment, this is possible solution.

根据我的评论,这是可能的解决方案。

To check which specific modifier key is pressed, you can use KeyboardEvent Location(see table support)

要检查按下了哪个特定的修饰键,您可以使用 KeyboardEvent Location请参阅表格支持

To support IE8, fortunately you could use already posted solution.

为了支持 IE8,幸运的是你可以使用已经发布的解决方案

Now the workaround is to set a global object with relevant properties regarding which modifier keys are held. Other ways without using global object would be possible of course.

现在的解决方法是设置一个全局对象,该对象具有关于所持有的修饰键的相关属性。不使用全局对象的其他方式当然是可能的。

Here, i capture event using relevant javascript listener method (jQuery doesn't support capturing phase). We capture event to handle case where keydown/keyupevents propagation would be stopped for some reason by already in-use code.

在这里,我使用相关的 javascript 侦听器方法捕获事件(jQuery 不支持捕获阶段)。我们捕获事件以处理keydown/keyup由于某种原因已在使用中的代码将停止事件传播的情况。

/* global variable used to check modifier keys held */
/* Note: if e.g control left key and control right key are held simultaneously */
/* only first pressed key is handled (default browser behaviour?)*/
window.modifierKeys = (function() {
  /* to handle modifier keys except AltGr which is key shortcut for controlRight + alt */
  var mKeys = {};
  /* to fire keydown event only once per key held*/
  var lastEvent, heldKeys = {};
  // capture event to avoid any event stopped propagation
  document.addEventListener('keydown', function(e) {
    if (lastEvent && lastEvent.which == e.which) {
      return;
    }
    lastEvent = e;
    heldKeys[e.which] = true;
    setModifierKey(e);
  }, true);
  // capture event to avoid any event stopped propagation
  document.addEventListener('keyup', function(e) {
    lastEvent = null;
    delete heldKeys[e.which];
    setModifierKey(e);
  }, true);

  function setModifierKey(e) {
    mKeys.alt = e.altKey;
    mKeys.ctrlLeft = e.ctrlKey && e.location === 1;
    mKeys.ctrlRight = e.ctrlKey && e.location === 2;
    mKeys.shiftLeft = e.shiftKey && e.location === 1;
    mKeys.shiftRight = e.shiftKey && e.location === 2;
  }
  return mKeys;
})();

/* on div click, check for global object */
$('.modifierKey').on('click', function() {
  console.log(modifierKeys);
  /* for demo purpose */
  $('.info').text(function() {
    var txt = [];
    for (var p in modifierKeys) {
      if (modifierKeys[p]) txt.push(p);
    }
    return txt.toString();
  });
})
/* for demo purpose */

.info:not(:empty) {
  border: 1px solid red;
  padding: .1em .5em;
  font-weight: bold;
}
.info:not(:empty):after {
  content: " held";
  font-weight: normal;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="modifierKey" tabindex="-1">
  DIV to catch modifier keys on click
</div>
<br>
<span class="info"></span>

As side notes:

作为旁注:

  • ALT GRkey is a shortcut key for CTRL-Right& ALTkeys
  • holding simultaneously two indentical modifier keys (e.g Shift-Left & Shift-Rigth keys), would result in only first one to be handled (seems like default browser behaviour, so anyway, seems right!)
  • ALT GRkey 是CTRL-Right&ALT键的快捷键
  • 同时按住两个相同的修饰键(例如 Shift-Left 和 Shift-Rigth 键),将只处理第一个(似乎是默认的浏览器行为,所以无论如何,看起来是对的!)

回答by user347594

Use js-hotkeys. It is a jQuery plugin.

使用js-hotkeys。它是一个 jQuery 插件。

This is a test to show what you are looking for. It also shows you how to capture left, right, up, down keys standard and those from numeric key pad (the one with numbers 2,4,6,8)! http://afro.systems.googlepages.com/test-static-08.html

这是一个测试,以显示您正在寻找什么。它还向您展示了如何捕获标准的左、右、上、下键和数字键盘(带有数字 2、4、6、8 的那个)! http://afro.systems.googlepages.com/test-static-08.html

回答by Otvazhnii

Easier than anything: you use keydown event to check if it's Ctrl(17) or Shift(16), you then use keyup event to check if it's Enter(13) and Ctrlor Shifthit before (on key down) cancel Ctrlor Shifton any keyup but Enter

比任何事情都容易:您使用 keydown 事件来检查它是Ctrl(17) 还是Shift(16),然后您使用 keyup 事件来检查它是否是Enter(13) 和/CtrlShift之前(按下键)取消CtrlShift在任何键上但Enter

回答by Vixed

Works like a charm! and on Chrome, Firefox, IE, and Edge too ;) https://jsfiddle.net/55g5utsk/2/

奇迹般有效!在 Chrome、Firefox、IE 和 Edge 上也是如此;) https://jsfiddle.net/55g5utsk/2/

var a=[];
function keyName(p){
    var cases = {16:'Shift',17:'CTRL',18:'Alt'};
    return cases[p] ? cases[p] : 'KeyCode: '+p;
}
function keyPosition(p){
    var cases = {1:'Left',2:'Right'};
    return cases[p] ? cases[p]+' ' : '';
}
$('input').on('keydown',function(e){
    a.push(keyPosition(e.originalEvent.location)+keyName(e.keyCode));
})
$('input').on('keyup',function(){
    var c='';
    var removeDuplicates = [];
    $.each(a, function(i, el){
        if ($.inArray(el, removeDuplicates) === -1) {
           removeDuplicates.push(el);
           c=c+(el)+' + ';
        }
    });
    a=[];
    alert(c.slice(0, -3))
});

Following, a version with the click eventhttp://jsfiddle.net/2pL0tzx9/

下面是一个带有点击事件的版本http://jsfiddle.net/2pL0tzx9/

var a=[];
function keyName(p){
    var cases = {16:'Shift',17:'CTRL',18:'Alt'};
    return cases[p] ? cases[p] : '';
}
function keyPosition(p){
    var cases = {1:'Left',2:'Right'};
    return cases[p] ? cases[p]+' ' : '';
}
$(document).on('keydown',function(e){
    a.push(keyPosition(e.originalEvent.location)+keyName(e.keyCode));
})
$('#my_id').on('click',function(){
    var c='';
    var removeDuplicates = [];
    a =a.filter(function(v){return v!==''});
    $.each(a, function(i, el){
      if ($.inArray(el, removeDuplicates) === -1){
          removeDuplicates.push(el);
          c=c+(el)+' + ';
      }
    });
    if (c) alert(c.slice(0, -3));
    a=[];   
});

回答by cyqsimon

Just thought I would add an answer appropriate for 2020.

只是想我会添加一个适合 2020 年的答案。



You can now also use MouseEvent.getModifierState()for this - it's supported by most browsersas of time of writing.

您现在也可以使用MouseEvent.getModifierState()它 -在撰写本文时,大多数浏览器都支持它。

document.addEventListener("click", (evn) => {
  const shift = evn.getModifierState("Shift");
  const ctrl = evn.getModifierState("Control");
  const alt = evn.getModifierState("Alt");

  console.log("Mouse pressed! Modifiers:");
  console.table({shift, ctrl, alt});
});

Example

例子

Caveats:

注意事项:

  • Notably, this API does not distinguishbetween left and right modifiers. If you care about that, you are kind of out of luck. But I imagine this only matters for a small number of use cases.
  • One of the main benefits of this API is that it supports modifiers other than shift, ctrl, and alt. However the specific behaviour is somewhat erratic across different OSes due to innate platform differences. Check herebefore you use them.
  • 值得注意的是,此 API不区分左右修饰符。如果你关心这一点,你就有点不走运了。但我想这只对少数用例很重要。
  • 其中的这个API的主要好处是,它支持比其他修饰shiftctrlalt。然而,由于先天的平台差异,不同操作系统的特定行为有些不稳定。在您使用它们之前检查这里

回答by Parth Patel

There are some reasons that right and left CTRL,SHIFT& ALTkeys are not distinguishable because 1. keyCodes are same 2. Many laptop keyboards may not have two control keys Taken a Reference : How can I tell if an event comes from right Ctrl key?

有一些原因,左,右CTRLSHIFTALT键是没有区别,因为1键编码是相同2.许多笔记本电脑的键盘可能不会采取了两个参考控制键: 我怎么能知道一个事件来自右Ctrl键?