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

发布于 2024-09-01 10:32:05 字数 306 浏览 7 评论 0原文

我如何识别在以下代码中按下了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"); }
});

How could I identify which Ctrl / Shift / Alt keys are pressed in the following code ?

$("#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"); }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

愿与i 2024-09-08 10:32:05

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

我还发现了这篇关于浏览器中的 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');
      }
    }
  }); 

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

I also found this wonder article about keypress, keyup, keydown event in browsers.
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');
      }
    }
  }); 
司马昭之心 2024-09-08 10:32:05
$('#someelement').bind('click', function(event){
   if(event.ctrlKey)
      console.log('ctrl');
   if(event.altKey)
      console.log('alt');
   if(event.shiftKey)
      console.log('shift');

});

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

$('#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.

青春有你 2024-09-08 10:32:05

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>

e.originalEvent.location returns 1 for left key and 2 for right key. Therefore you can detect which modifier key is pressed like following. 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>

Smile简单爱 2024-09-08 10:32:05

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

var altKeyPressed = instanceOfMouseEvent.altKey

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

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

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

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

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

も让我眼熟你 2024-09-08 10:32:05

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


您现在也可以使用 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});
});

示例

注意事项:

  • 值得注意的是,此 API 不区分左修饰符和右修饰符。如果你关心这一点,那你就不太走运了。但我想这只对少数用例重要。
  • 此 API 的主要优点之一是它支持 shiftctrlalt 以外的修饰符。然而,由于固有的平台差异,不同操作系统之间的具体行为有些不稳定。在使用它们之前,请先检查此处

Just thought I would add an answer appropriate for 2020.


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

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 distinguish between 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 here before you use them.
葬心 2024-09-08 10:32:05

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

要检查按下了哪个特定修饰键,您可以使用 KeyboardEvent Location (查看表格支持)

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

现在的解决方法是设置一个全局对象,其中包含与持有哪些修饰键相关的属性。当然,不使用全局对象的其他方法也是可能的。

在这里,我使用相关的 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>

旁注:

  • ALT GR 键是 CTRL-RightCTRL-Right 的快捷键。 ALT
  • 同时按住两个相同的修饰键(例如 Shift-Left 和 Shift-Left
    Shift-Right 键),将导致仅处理第一个
    (似乎是默认浏览器行为,所以无论如何,似乎是正确的!)

Following my comment, this is possible solution.

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

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

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/keyup events propagation would be stopped for some reason by already in-use code.

/* 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 GR key is a shortcut key for CTRL-Right & ALT
    keys
  • 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!)
久伴你 2024-09-08 10:32:05

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

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

Use js-hotkeys. It is a jQuery plugin.

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

辞别 2024-09-08 10:32:05

比任何事情都简单:您使用 keydown 事件来检查它是否是 Ctrl (17) 或 Shift (16),然后使用 keyup 事件来检查它是否是 Enter< /kbd> (13) 和 CtrlShift 之前按下(按下键时)
取消任何按键上的 CtrlShift,但 Enter 除外

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 Ctrl or Shift hit before (on key down)
cancel Ctrl or Shift on any keyup but Enter

浅笑依然 2024-09-08 10:32:05

效果就像一个魅力! Chrome、Firefox、IE 和 Edge 上也支持 ;) https://jsfiddle.net/55g5utsk/2/< /a>

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

以下是带有点击事件的版本
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=[];   
});

Works like a charm! and on Chrome, Firefox, IE, and Edge too ;) 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/

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=[];   
});
原来分手还会想你 2024-09-08 10:32:05

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

There are some reasons that right and left CTRL,SHIFT & ALT keys 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文