keydown 的侦听器被触发多次而不是一次

发布于 2025-01-13 02:13:18 字数 437 浏览 1 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

手长情犹 2025-01-20 02:13:18

请改用 keyup。只要按住某个键,就会触发 keydown 事件。 keyup 仅在释放按键时触发。

var undoButton = document.getElementById('undoButton');
undoButton.onclick = undoFunction;
document.addEventListener("keyup", (e) => {
  if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
    e.preventDefault();
    undoFunction();
  }
});

function undoFunction() {
  console.log("undo function...");
}
<input id="undoButton" type="button" value="Undo" />

Use keyup instead. The keydown event triggers as long a key is hold down. keyup only triggers when a key is released.

var undoButton = document.getElementById('undoButton');
undoButton.onclick = undoFunction;
document.addEventListener("keyup", (e) => {
  if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
    e.preventDefault();
    undoFunction();
  }
});

function undoFunction() {
  console.log("undo function...");
}
<input id="undoButton" type="button" value="Undo" />

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文