keydown 的侦听器被触发多次而不是一次
我有以下代码:
undoButton.onclick = undoFunction;
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
e.preventDefault();
undoFunction();
}
});
function undoFunction() {
console.log("undo function...");
}
当我单击按钮时,除此之外,函数代码运行一次,console.log也是如此,但是当我使用击键时,函数运行多次,最多可达数百次- 在某些情况下称为循环。有什么建议吗?我尝试使用 e.repeat = false
但没有成功。谢谢!
I have the following code:
undoButton.onclick = undoFunction;
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
e.preventDefault();
undoFunction();
}
});
function undoFunction() {
console.log("undo function...");
}
When I click the button, as excepted, the function code runs once, and so does the console.log, but when I use the key stroke, the function is running a multiple times, up to hundreds of so-called loops at some scenarios. Any suggestion why? I tried to used e.repeat = false
but had no luck. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请改用 keyup。只要按住某个键,就会触发 keydown 事件。 keyup 仅在释放按键时触发。
Use keyup instead. The keydown event triggers as long a key is hold down. keyup only triggers when a key is released.