简体   繁体   English

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

[英]Check Ctrl / Shift / Alt keys on 'click' event

How could I identify which Ctrl / Shift / Alt keys 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"); }
});

Well you this wont work in all browsers just IE 8. Microsoft implemented the ability to determine which (right/left) key was pressed.好吧,这不适用于仅 IE 8 的所有浏览器。Microsoft 实现了确定按下哪个(右/左)键的功能。 Here is a link http://msdn.microsoft.com/en-us/library/ms534630(VS.85).aspx这是一个链接http://msdn.microsoft.com/en-us/library/ms534630(VS.85).aspx

I also found this wonder article about keypress, keyup, keydown event in browsers.我还发现了这篇关于浏览器中的 keypress、keyup、keydown 事件的精彩文章。 http://unixpapa.com/js/key.html 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');
      }
    }
  }); 
$('#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.我不知道是否可以在单击事件中检查左/右键,但我认为这是不可能的。

e.originalEvent.location returns 1 for left key and 2 for right key. e.originalEvent.location为左键返回 1,为右键返回 2。 Therefore you can detect which modifier key is pressed like following.因此,您可以检测按下了哪个modifier键,如下所示。 Hope this will help you.希望这会帮助你。

 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>

In most instances the ALT , CTRL ,and SHIFT key booleans will work to see if those keys were pressed.在大多数情况下, ALTCTRLSHIFT键布尔值将用于查看是否按下了这些键。 For example:例如:

var altKeyPressed = instanceOfMouseEvent.altKey

When called upon, it will return true or false.当被调用时,它将返回 true 或 false。 For more info, go to https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey有关更多信息,请访问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)的方法,它在按下元键时起作用。

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) .在这里,我使用相关的 javascript 侦听器方法捕获事件(jQuery 不支持捕获阶段) We capture event to handle case where keydown/keyup events propagation would be stopped for some reason by already in-use code.我们捕获事件来处理keydown/keyup事件传播由于某种原因被已经使用的代码停止的情况。

 /* global variable used to check modifier keys held */ /* Note: if eg 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 GR key is a shortcut key for CTRL-Right & ALT keys ALT GR键是CTRL-Right & ALT键的快捷键
  • holding simultaneously two indentical modifier keys (eg Shift-Left & Shift-Rigth keys), would result in only first one to be handled (seems like default browser behaviour, so anyway, seems right!)同时按住两个相同的修饰键(例如 Shift-Left 和 Shift-Rigth 键),将只处理第一个(似乎是默认的浏览器行为,所以无论如何,看起来是对的!)

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 browsers as 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});
});

例子

Caveats:注意事项:

  • Notably, this API does not distinguish between left and right modifiers.值得注意的是,此 API不区分左右修饰符。 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 .此 API 的主要优点之一是它支持除shiftctrlalt之外的修饰符。 However the specific behaviour is somewhat erratic across different OSes due to innate platform differences.然而,由于先天的平台差异,不同操作系统的特定行为有些不稳定。 Check here before you use them.在您使用它们之前检查这里

Use js-hotkeys .使用js-hotkeys It is a jQuery plugin.它是一个 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)!它还向您展示了如何捕获标准的左、右、上、下键和数字键盘(带有数字 2、4、6、8 的那个)! http://afro.systems.googlepages.com/test-static-08.html http://afro.systems.googlepages.com/test-static-08.html

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

左右CTRLSHIFTALT键无法区分的原因有一些,因为 1. 键码相同 2. 许多笔记本电脑键盘可能没有两个控制键 参考: 如何判断事件是否来自右 Ctrl 键?

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 event http://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=[];   
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM