jQuery处理按键组合

Gau*_*rav 18 javascript jquery

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

在下面的代码中,我尝试做类似的事情:

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

Sam*_*son 34

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

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

  • +1表示ctrlKey.但我提供的链接也适用于非特殊键 (3认同)

Vax*_*dze 5

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

注意:此示例是捕获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
        }
      }
    })
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,接受的答案对我也不起作用。感谢您添加您的解决方案。奇迹般有效。 (3认同)