javascript jQuery 处理按键组合

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

jQuery handling keypress combinations

javascriptjquery

提问by Gaurav

I know that when keypressevent occurs then we can access which key is pressed by object's event property keycode, but I need to know how do we can handle keypresscombinations through jQuery like ctrl + D..etc?

我知道当keypress事件发生时,我们可以访问对象的事件属性按下了哪个键keycode,但我需要知道我们如何keypress通过 jQuery处理组合,例如ctrl + D..etc?

In the following code I tried to do something like :

在以下代码中,我尝试执行以下操作:

$(document).on("keypress", function(e) { 
    if( /* what condition i can give here */ )           
        alert("you pressed cntrl + Del");
});

回答by Sampson

jQuery already handles this for you:

jQuery 已经为你处理了这个:

if ( e.ctrlKey && ( e.which === 46 ) ) {
  console.log( "You pressed CTRL + Del" );
}

回答by Vaxo Basilidze

I know that this is an old question that has already been answered, but the answer marked as correct did not work for me. Here is a simple and easy method for catching the key combinations I wrote:

我知道这是一个已经回答的老问题,但标记为正确的答案对我不起作用。这是一个简单易行的方法来捕捉我写的组合键:

NOTE:This example is catching ctrl + spacecombination, but you can easily change it to any other keys.

注意:此示例是捕获ctrl + space组合,但您可以轻松地将其更改为任何其他键。

    var ctrlPressed = false; //Variable to check if the the first button is pressed at this exact moment
    $(document).keydown(function(e) {
      if (e.ctrlKey) { //If it's ctrl key
        ctrlPressed = true; //Set variable to true
      }
    }).keyup(function(e) { //If user releases ctrl button
      if (e.ctrlKey) {
        ctrlPressed = false; //Set it to false
      }
    }); //This way you know if ctrl key is pressed. You can change e.ctrlKey to any other key code you want

    $(document).keydown(function(e) { //For any other keypress event
      if (e.which == 32) { //Checking if it's space button
        if(ctrlPressed == true){ //If it's space, check if ctrl key is also pressed
          myFunc(); //Do anything you want
          ctrlPressed = false; //Important! Set ctrlPressed variable to false. Otherwise the code will work everytime you press the space button again
        }
      }
    })