如何使用 jQuery 检查在单击事件期间是否按下了某个键?

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

How can I check if a key is pressed during the click event with jQuery?

jqueryeventskeyboardclick

提问by daniel smith

I would like to catch a click event with jQuery and be able to tell if a key was pressed at the same time so I can fork within the callback function based on the keypress event.

我想用 jQuery 捕捉点击事件,并能够判断是否同时按下了一个键,以便我可以根据按键事件在回调函数中分叉。

For example:

例如:

$("button").click(function() {
    if([KEYPRESSED WHILE CLICKED]) {
        // Do something...
    } else {
        // Do something different...
    }
});

Is this possible at all or how can it be done if it is possible?

这完全可能吗,或者如果可能的话怎么做?

回答by kkyy

You can easily detect the shift, alt and control keys from the event properties;

您可以从事件属性中轻松检测到 shift、alt 和 control 键;

$("button").click(function(evt) {
  if (evt.ctrlKey)
    alert('Ctrl down');
  if (evt.altKey)
    alert('Alt down');
  // ...
});

See quirksmodefor more properties. If you want to detect other keys, see cletus's answer.

有关更多属性,请参阅quirksmode。如果要检测其他键,请参阅cletus 的回答

回答by cletus

You need to separately track the key status using keydown()and keyup():

您需要使用keydown()和单独跟踪密钥状态keyup()

var ctrlPressed = false;
$(window).keydown(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = true;
  }
}).keyup(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = false;
  }
});

See the list of key codes. Now you can check that:

请参阅密钥代码列表。现在您可以检查:

$("button").click(function() {
  if (ctrlPressed) {
    // do something
  } else {
    // do something else
  }
});

回答by Arun Prasad E S

I was able to use it with JavaScript alone

我可以单独使用 JavaScript

 <a  href="" onclick="return Show(event)"></a>

  function Show(event) {
            if (event.ctrlKey) { 
                 alert('Ctrl down');
            }
     }

回答by vr_driver

Without stealing @Arun Prasad's thunder, here is a pure JS snippet I rehashed to stop the default action, which would otherwise open a new window if CTL+click is pressed.

在不窃取@Arun Prasad 的雷声的情况下,这里是一个纯 JS 片段,我重新整理以停止默认操作,否则如果按下 CTL+click 将打开一个新窗口。

function Show(event) 
{
  if (event.ctrlKey) 
  {
    alert('Ctrl held down which clicked');
  } 
  else 
  {
    alert('Ctrl NOT pressed');
  }
  return false
}
<p>Hold down CTL on the link to get a different message</p>

<a href="" onclick="return Show(event)">click me</a>