簡體   English   中英

javascript如何檢測鍵盤輸入

[英]javascript how to detect keyboard input

當專注於某個輸入時,用戶按某種組合鍵,例如“ 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');
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM