gpt4 book ai didi

javascript - 如何检测单个控件的按键事件而不是组合键?

转载 作者:行者123 更新时间:2023-11-29 14:45:51 26 4
gpt4 key购买 nike

很容易检测控制键事件

document.addEventListener('keyup', handler, false);

...

function handler(e) {
var key = e.which || e.keyCode;

if (key == 17) { // Control key
...
}
}

问题是任何组合键如control-ccontrol-v也会触发事件,似乎事件处理程序无法区分单个 controlcontrol-c control kbd>.

我想要的是只允许按下并释放单个键,而不是组合键来触发事件。

最佳答案

这个怎么样:

var controlConsidered = false;

function ctrlPressed() {
console.log("Control was pressed.");
}

function keydownhandler(e) {
var key = e.which || e.keyCode;
controlConsidered = (key == 17);
}

function keyuphandler(e) {
var key = e.which || e.keyCode;
if (key == 17 && controlConsidered) {
ctrlPressed();
}
}

document.addEventListener('keydown', keydownhandler, false);
document.addEventListener('keyup', keyuphandler, false);

关于javascript - 如何检测单个控件的按键事件而不是组合键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33060901/

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