jQuery处理键盘按键组合

23
我知道当发生 keypress 事件时,我们可以通过对象的事件属性 keyCode 访问按下了哪个键,但我想知道如何通过 jQuery 处理类似 ctrl + Dkeypress 组合键?
在下面的代码中,我尝试做一些类似以下的事情:
$(document).on("keypress", function(e) { 
    if( /* what condition i can give here */ )           
        alert("you pressed cntrl + Del");
});

3
请看这个链接:https://dev59.com/Fmgv5IYBdhLWcg3wXPot#10655316顺带一提,我更喜欢我的回答(嘿嘿)。 - Parth Thakkar
2个回答

40

jQuery 已经为您处理了这个问题:

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

3
+1 表示按下 Ctrl 键。但是我提供的链接也适用于非特殊键。 - Parth Thakkar

6

我知道这是一个早已有答案的老问题,但被标记为正确答案的方法对我不起作用。下面是我写的一个简单易懂的捕获键盘组合键的方法:

注意:此示例捕获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
        }
      }
    })

3
非常好,对我来说已经接受的答案也没用。感谢您添加解决方案。非常有效。 - Jonathan Laliberte
@JonathanLaliberte 很高兴能帮忙 :) - Vaxo Basilidze
一样,其他方法都没用。干得好 :) - Ivana Bakija

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接