【问题标题】:jQuery handling keypress combinationsjQuery 处理按键组合
【发布时间】:2012-05-27 03:51:40
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

jQuery 已经为你处理好了:

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

【讨论】:

  • ctrlKey +1。但我提供的链接也适用于非特殊键
【解决方案2】:

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

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

【讨论】:

  • 太棒了,接受的答案对我也不起作用。感谢您添加解决方案。像魅力一样工作。
  • @JonathanLaliberte 乐于助人:)
猜你喜欢
  • 2013-02-28
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多