在这种情况下,如果单击右箭头按钮,我如何每 5 秒检查一次?这是我试过的。它只工作一次,永远不会再次检查。我做错了什么?
setInterval(KeyPressed, 5000);
window.onkeydown = KeyPressed;
function KeyPressed(k) {
if (k.keyCode == 39) {
alert("Right Arrow");
}
}
最佳答案
也许是这个?
检查最后点击的键是否是箭头
var lastKey = "", tId = setInterval(testKey, 5000);
window.onkeydown = KeyPressed;
function KeyPressed(k) {
lastKey = k.keyCode;
}
function testKey() {
if (lastKey == 39) {
console.log("Arrow pressed as last key in the last 5 secs");
lastKey=""; // clear it for next time
}
}
检查箭头是否在最后 5 秒内被点击
var lastKey = "", tId = setInterval(testKey, 5000), arrow = "";
window.onkeydown = KeyPressed;
function KeyPressed(k) {
lastKey = k.keyCode;
if (lastKey == 39) {
arrow = new Date();
console.log("pressed arrow");
}
}
function testKey() {
if (arrow) {
console.log("Arrow pressed at least once in the last 5 secs - at "+arrow);
}
arrow="";
}
关于Javascript 如果单击特定键,我如何每 5 秒检查一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50386836/