問題描述
我目前正在使用這個 Javascript 按鍵代碼在按鍵時觸發事件:
I am currently using this Javascript keypress code to fire events upon keypress:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
});
但我想知道的是,我是否可以綁定兩個鍵的組合而不是綁定一個鍵.我可以做類似的事情嗎:
but what I am wondering is if I can instead of binding one key bind a combination of two keys. Could I possibly do something like:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39 && 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});
推薦答案
如果你想一次檢查多個鍵,你應該只使用一個常規鍵和一個或多個修飾鍵(alt/shift/ctrl),因為你不能確保在用戶的鍵盤上實際上可以同時按下兩個常規鍵(實際上,它們總是可以按下,但由于鍵盤的接線方式,PC 可能無法理解).
If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).
您可以使用 e.altKey、e.ctrlKey、e.shiftKey 字段來檢查是否按下了匹配的修飾鍵.
You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.
例子:
$(document).keydown(function(e) {
if(e.which == 98 && e.ctrlKey) {
// ctrl+b pressed
}
});
這篇關于將多個鍵綁定到 Keypress 事件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!