function Press(){
document.querySelector("body").addEventListener("keyup", event => {
if(event.key !== "Shift") return;
document.getElementById("myElement").click();
event.preventDefault();
});
}
我设置键按Shift 1次。我怎么能把它设置为3个快时间?所以在Shift Shift之后,一个事件(document.getElementById("髓元素".click())被执行?
更新:
这是使用@ decize help制作的工作代码
function Press(){
document.addEventListener("keyup", event => {
if(event.key !== "Shift") return;
shift_pressed = typeof shift_pressed !== 'undefined' ? shift_pressed : 0;
shift_pressed++;
setTimeout(() => {
shift_pressed= shift_pressed-1 >= 0 ? shift_pressed-1 : 0;
}, 1000);
if (shift_pressed===3){
document.getElementById("myElement").click();
shift_pressed=0;
}
event.preventDefault();
});
}
感谢大家的帮助
每按三次Shift键就触发点击
function Press(){
const THRESHOLD = 250;
let counter = 0;
let millis = Date.now();
document.querySelector("body").addEventListener("keyup", event => {
if(event.key !== "Shift") return;
if(Date.now()-millis > THRESHOLD) counter = 0;
if(++counter%3===0) {
document.getElementById("myElement").click();
event.preventDefault();
}
millis = Date.now();
});
}
创建setTimeout
用于清除单击Shift的计数器,并定义clearTimeout
用于清除每次单击的超时时间
document.getElementById("myElement").onclick = () => {
console.log('Hello World!');
}
let clearTime = 1000;
let counterShift = 0;
let timeout;
document.querySelector("body").addEventListener("keyup", event => {
if(event.key !== "Shift") return;
clearTimeout(timeout);
counterShift++;
console.log('number click:',counterShift);
if(counterShift == 3) {
document.getElementById("myElement").click();
event.preventDefault();
counterShift = 0;
}
timeout = setTimeout(()=>{
counterShift = 0;
}, clearTime);
});
<button id="myElement">Test</button>