21

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

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

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

2 回答 2

39

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

if ( e.ctrlKey && ( e.which === 46 ) ) {
  console.log( "You pressed CTRL + Del" );
}
于 2012-05-20T08:09:43.423 回答
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
        }
      }
    })
于 2018-09-24T12:03:57.727 回答