2017-07-27 90 views
4

當按下數字鍵盤側的加號鍵時,我有一個要求將+鍵作爲製表鍵複製的請求。如何確定哪個「+」鍵被按下?

看來上面的字母加號鍵在需要shift鍵,加號鍵,其中數字是在按鍵板配置都具有43

數字號碼,我怎麼能確定哪個+鍵被按下?

更新: 我用這個例子中,「https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_key_keycode」爲指出以下事實並不是這樣做的正確方法。

回答

6

每個鍵的鍵碼是不同的。數字鍵盤= 107,頂行= 187

你可以用它來驗證它自己的鍵盤上:

$('#text').on('keydown', function (e) { 
 
    $('label').text(e.which); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="text" /> 
 
<label></label>

您還可以使用在現代瀏覽器的key財產(IE9 + )來檢測哪個鍵被輸出,而不必擔心使用哪個鍵來生成它:

$('#text').on('keydown', function (e) { 
 
    if (e.key == '+') 
 
    console.log('You typed a plus symbol!'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="text" /> 
 
<label></label>

+0

你可以告訴你使用的代碼? – eaglei22

+0

剛剛編輯它在 –

+0

好吧謝謝。嗯,我使用這個版本: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_key_keycode 他們來了43 – eaglei22

1

這兩個鍵產生兩個不同的鍵碼。您可以測試正確的:

$(document).on("keydown", function(evt){ 
 
    switch (evt.keyCode){ 
 
    case 107: 
 
     console.log("You pressed '+' on the number pad"); 
 
     break; 
 
    case 187: 
 
     console.log("You pressed SHIFT '+' on main keyboard"); 
 
     break;  
 
    }  
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Just click once over here to give the "document" focus and then press the + key(s)