2016-05-22 50 views
1

有沒有人知道如何檢測按下鍵碼「+1輸入」和「-1輸入」在Javascript中,請。 我想檢測一次按鍵碼而不是一次。Javascript按下鍵碼「+1輸入」和「-1輸入」

但是當我寫下面的代碼時,沒有給出任何效果。

// +1 enter 
$(document).keydown(function(e) { 
    if (e.keyCode == 107 && e.keyCode == 49 && e.keyCode == 13) { 
    window.alert("+1"); 
    } 
}); 

// -1 enter 
$(document).keydown(function(e) { 
    if (e.keyCode == 109 && e.keyCode == 49 && e.keyCode == 13) { 
    window.alert("-1"); 
    } 
}); 

請注意您的專業意見。

+0

你應該使用'||',而不是'&&'。一個單一的keypess如何可以同時使用3個不同的角色? –

+0

我的意思是按下+,1,輸入或 - ,1,一個一個輸入,但在短時間內 – CKH

+0

您是否打算實現您要查找的內容庫(按鍵序列),還是需要堅持香草JS和jQuery? – jdphenix

回答

0

爲了做到這一點,您需要能夠跟蹤以前的按鍵。請嘗試以下操作:

// These are just used to display the result in the DOM--you can delete this 
 
var $keyCodes = document.getElementById('key-codes'); 
 
var $result = document.getElementById('result'); 
 

 
// Used to keep track of your key presses 
 
var trackKeyCodes = (function() { 
 
    // Keep a private array of key codes to track 
 
    var keyCodes = []; 
 
    // This is the actual function that gets stored in trackKeyCodes 
 
    return function(keyCode) { 
 
    // Only store the last 3 key codes 
 
    if (keyCodes.length === 3) keyCodes.splice(0, 1); 
 
    // Add the next key code 
 
    keyCodes.push(keyCode); 
 
    // This just displays it in the DOM for you to see--you can delete this 
 
    $keyCodes.innerHTML = keyCodes.join(', '); 
 
    return keyCodes; 
 
    }; 
 
})(); 
 
// Used to actually check the key presses 
 
var checkKeyCodes = function(keyCodes, first, second, third) { 
 
    return keyCodes[0] === first && keyCodes[1] === second && keyCodes[2] === third; 
 
}; 
 

 
// +1 enter 
 
$(document).keydown(function(e) { 
 
    var keyCodes = trackKeyCodes(e.keyCode); 
 
    if (checkKeyCodes(keyCodes, 107, 49, 13)) { 
 
     $result.innerHTML = '+ 1'; 
 
    } else if (checkKeyCodes(keyCodes, 109, 49, 13)) { 
 
     $result.innerHTML = '- 1'; 
 
    } else { 
 
     $result.innerHTML = ''; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p> 
 
KeyCodes: <span id="key-codes">-</span> 
 
</p> 
 
<p> 
 
Result: <span id="result">-</span> 
 
</p>

+0

謝謝。但是代碼「window.alert」應該放在代碼中哪裏?而且你的代碼是什麼意思? – CKH

0

您可以使用下面的功能:

$(document).keydown((function() { 
    var codes = []; 
    return function(e) { 
     if (e.keyCode == 107 || e.keyCode == 109 || e.keyCode == 49 || e.keyCode == 13) { 
      codes.push(e.keyCode); 
      if (codes.toString().indexOf('107,49,13') >= 0) { 
       alert('+1'); 
       codes.splice(0, codes.length); 
      } else if (codes.toString().indexOf('109,49,13') >= 0) { 
       alert('-1'); 
       codes.splice(0, codes.length); 
      } 
     } else { 
      codes.splice(0, codes.length); 
     } 
    }; 
})()); 

基本上,你只需要找到存儲先前按鍵,然後檢查他們的一些方法每次按下一個新鍵。在這種情況下,它存儲在一個IIFE閉包內的變量中。

JSFiddle

+0

但是,您在JSFiddle中的代碼不起作用。 – CKH

+0

@CKH是的,你必須點擊右下角的框並使用數字鍵盤的'+'和'-'鍵。 –

+0

不,當我按下num lock時,按+或 - ,1並逐個輸入,則不會提示警告窗口。 – CKH