有人知道如何检测按键码" +1输入"和" -1输入"请在Javascript中。 我想检测一键式按键码而不是一次按键。
但是当我写下面的代码时,没有给出任何效果。
// +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 :(得分: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>
&#13;
答案 1 :(得分: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闭包内的变量中。