捕获“控制”在Javascript中使用keydown新闻事件 [英] Capturing "control" keydown press event in Javascript

查看:96
本文介绍了捕获“控制”在Javascript中使用keydown新闻事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在下面的代码中,CTRL UP将会使用Ctrl按预期显示,但只有当我按住另一个键时,才会显示CTRL DOWN,例如shift。

 < html> 
< head>
< script type =text / javascript>
window.addEventListener(keyup,function(event){
//绑定到Mac命令和控制(Win / Linux)
if(event.ctrlKey){
console.log(CTRL UP);
}
},false);

window.addEventListener(keydown,function(event){
//绑定到Mac命令和控制命令(Win / Linux)
if(event .ctrlKey){
console.log(CTRL DOWN);
}
},false);

< / script>
< / head>
< body>
Ctrl Demo
< / body>
< / html>

有没有办法让CTRL DOWN键事件按预期工作,当ctrl是按下并自行保存?



注意:我试图让这个功能在谷歌浏览器扩展中运行,所以使用Chrome特定的API或技巧来完成这项工作是完全没问题的。我在Ubuntu上使用Google Chrome 15.0.874.83测试版。

解决方案

您的代码适用于我,以及以下jQuery。 (Chrome)

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

使用alert有点尴尬,因为它会阻止进程并且看不到任何关键状态更改在对话框启动时发生。我建议使用console.info/log/debug


I'm trying to figure out when the user presses the "control" key in an HTML page using Javascript.

In the following code "CTRL UP" will appear as expected, but "CTRL DOWN" will only appear if I also press another key, e.g. "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?

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.

解决方案

Your code works for me, as does the following jQuery. (Chrome)

$(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

这篇关于捕获“控制”在Javascript中使用keydown新闻事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆