【问题标题】:javascript how to detect keyboard inputjavascript如何检测键盘输入
【发布时间】:2015-02-16 20:15:40
【问题描述】:

当专注于某个输入时, 用户按下某种组合键,例如“ctrl+e”, 我想在输入中显示“ctrl+e”。

下次用户按下另一个组合键时, 它会清理输入并显示新的。

我怎样才能做到这一点? 我在寻找一些 javascript 插件, 但它们最适合检测某些输入。

像这样: https://github.com/OscarGodson/jKey

$("input").jkey("i",function(){
    jkey.log("You pressed the i key inside of an input.");
});

非常感谢。

【问题讨论】:

标签: javascript jquery keyboard


【解决方案1】:

另一种方法(不需要插件)它只使用传入的event object 的 .ctrlKey 属性。它指示在事件发生时是否按下了 Ctrl,如下所示:

$(document).keypress("c",function(e) {
  if(e.ctrlKey)
    alert("Ctrl+C was pressed!!");
});

更新

$(document).on('keypress','input',function(e){
    if ( e.ctrlKey && ( String.fromCharCode(e.which) === 'c' || String.fromCharCode(e.which) === 'C' ) ) {
        console.log( "You pressed CTRL + C" );
    }
});

【讨论】:

  • 我不知道用户会在输入中按什么,如果我使用这种方式,我必须为各种可能的输入编写许多函数?
【解决方案2】:

并非所有浏览器都允许捕获 cntrl 按键。这将适用于其余部分

$( document ).keypress(function(e) {
    var ch = String.fromCharCode(e.charCode);
    if(e.ctrlKey){
      console.log('cntrl+'+ch+' was pressed');
    }else{
      console.log(ch+' was pressed');
    }
});

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2017-11-23
    • 2014-07-08
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多