有人知道如何在Javascript中检测按键代码“+1 Enter”和“-1 Enter”吗?我想检测何时一一按下键码而不是一次按下键码。
但是当我编写以下代码时,没有给出任何效果。
// +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");
}
});
请提供专业意见。
为了实现这一点,您需要能够跟踪以前按下的键。请尝试以下操作:
// 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';
} khác {
$result.innerHTML = '';
}
});
KeyCodes: -
Result: -
Tôi là một lập trình viên xuất sắc, rất giỏi!