javascript如何检测键盘输入

时间:2014-12-18 05:37:19

标签: javascript jquery keyboard

当关注某个输入时, 用户按下组合键,如" 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.");
});

非常感谢。

2 个答案:

答案 0 :(得分:2)

另一种方法(不需要插件)只需使用传入的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" );
    }
});

答案 1 :(得分:0)

并非所有浏览器都允许捕获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');
    }
});
相关问题