JavaScript 如何检测键盘输入

javascript how to detect keyboard input

本文关键字:键盘 输入 检测 何检测 JavaScript      更新时间:2023-09-26

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

多谢。

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

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