Javascript 在Javascript中捕获“控制”按键按下事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7801174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capturing "control" keydown press event in Javascript
提问by oneself
I'm trying to figure out when the user presses the "control" key in an HTML page using Javascript.
我试图弄清楚用户何时使用 Javascript 在 HTML 页面中按下“控制”键。
In the following code "CTRL UP" will appear as expected, but "CTRL DOWN" will only appear if I alsopress another key, e.g. "shift".
在下面的代码中,“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>
Is there any way to get the "CTRL DOWN" key event to work as expected, when ctrl is pressed and held down by itself?
当 ctrl 被单独按下并按住时,有没有办法让“CTRL DOWN”键事件按预期工作?
NOTE: I'm trying to get this to work in a Google Chrome extension, so using Chrome specific APIs or tricks to make this work is completely fine. I'm using Google Chrome 15.0.874.83 beta on Ubuntu.
注意:我试图让它在 Google Chrome 扩展程序中工作,所以使用 Chrome 特定的 API 或技巧来完成这项工作是完全没问题的。我在 Ubuntu 上使用 Google Chrome 15.0.874.83 beta。
回答by Miles
Your code works for me, as does the following jQuery. (Chrome)
您的代码对我有用,下面的 jQuery 也是如此。(铬合金)
$(window).keydown(function(e){
if (e.ctrlKey)
console.log('Control Down');
});
Using alert is a little awkward because it blocks the process and you won't see any key state changes that occur while the dialog is up. I recommend using console.info/log/debug
使用警报有点尴尬,因为它会阻止进程,并且您不会看到在对话框启动时发生的任何关键状态更改。我建议使用 console.info/log/debug
回答by Tim Down
If you just want to detect the Ctrlkey being pressed on its own, the following will work (although bear in mind that addEventListener
is not supported in IE < 9, where you'd need to use attachEvent
or onkeydown
instead):
如果您只想检测Ctrl自己按下的键,以下将起作用(但请记住,addEventListener
IE < 9 不支持,您需要使用attachEvent
或onkeydown
代替):
window.addEventListener("keydown", function(event) {
// Bind to both command (for Mac) and control (for Win/Linux)
if (event.keyCode == 17) {
alert("Ctrl");
}
}, false);