gpt4 book ai didi

Javascript 按键代码 "+1 enter"和 "-1 enter"

转载 作者:行者123 更新时间:2023-11-28 05:59:48 30 4
gpt4 key购买 nike

有人知道如何在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';
} 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>

关于Javascript 按键代码 "+1 enter"和 "-1 enter",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376401/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com