在JS中检测双Ctrl按键 [英] Detect double Ctrl keypress in JS

查看:81
本文介绍了在JS中检测双Ctrl按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义CMS,想添加一个快捷菜单",该快捷方式是在300毫秒之内两次按下 Ctrl 键触发的. 我使用原型,所以我的出发点显然是:

I have a custom CMS and would like to add a "shortcuts menu" triggered by the pressing of the Ctrl key twice within, say, 300 milliseconds. I use prototype, so my starting point obviously is:

Event.observe(document, 'keypress', function(event)
  { if(event.keyCode == Event.KEY_XYZ) { show_shortcuts});

目前,我的方法是使用当前时间(以毫秒为单位)填充全局变量,并检查每个按键是否在不到300毫秒之前发生了按键.

My approach at the moment would be populating a global variable with the current time in milliseconds, and checking on each keypress whether a keypress has happened less than 300 milliseconds ago.

但是也许有一个更优雅的解决方案?

But maybe there is a more elegant solution?

推荐答案

这应该有效.如果未同时按下其他键(例如Alt或Shift),则可能需要添加一些进一步的检查.希望它是自我解释的,如果不只是问我,我会提供澄清.

This should work. Maybe add some further checking if not some other key like Alt or Shift are pressed at the same time. Hope it is self explanatory, if not just ask and I provide clarification.

var dblCtrlKey = 0;
Event.observe(document, 'keydown', function(event) {
  if (dblCtrlKey != 0 && event.keyCode == 17) {
    alert("Ok double ctrl");
  } else {
    dblCtrlKey = setTimeout('dblCtrlKey = 0;', 300);
  }
});

这篇关于在JS中检测双Ctrl按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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