捕捉“control"JavaScript中的按键按下事件

Capturing "control" keydown press event in JavaScript

本文关键字:事件 JavaScript control quot 捕捉      更新时间:2023-09-26

我想弄清楚用户在使用JavaScript的HTML页面中何时按下控制键。

在以下代码中"CTRL UP"将按预期显示,但是"CTRL DOWN"只有当我同时按另一个键时才会出现,例如shift

<html>
<head>
<script type="text/javascript">
window.addEventListener("keyup", function(event) {
  // Bind to both command (for Mac) and control (for Win/Linux)
  if (event.ctrlKey) {
    console.log("CTRL UP");
  }
}, false);
window.addEventListener("keydown", function(event) {
  // Bind to both command (for Mac) and control (for Win/Linux)
  if (event.ctrlKey) {
    console.log("CTRL DOWN");
  }
}, false);
</script>
</head>
<body>
Ctrl Demo
</body>
</html>

有没有办法得到"CTRL DOWN"当ctrl被按下时,键事件按预期工作?

注意:我试图让这个工作在谷歌Chrome扩展,所以使用Chrome特定的api或技巧,使这项工作是完全好的。我在Ubuntu上使用的是Google Chrome 15.0.874.83测试版

您的代码为我工作,就像下面的jQuery。(铬)

$(window).keydown(function(e){
    if (e.ctrlKey)
        console.log('Control Down');
});

使用alert有点尴尬,因为它阻塞了进程,当对话框打开时,您不会看到任何键状态的变化。我建议使用console.info/log/debug

如果你只是想检测Ctrl键被自己按下,下面将工作(尽管记住addEventListener不支持在IE <9,你需要使用attachEventonkeydown代替):

window.addEventListener("keydown", function(event) {
    // Bind to both command (for Mac) and control (for Win/Linux)
    if (event.keyCode == 17) {
        alert("Ctrl");
    }
}, false);