Detect double Ctrl keypress in JS

青春壹個敷衍的年華 提交于 2020-05-13 05:03:51

问题


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});

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?


回答1:


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);
  }
});



回答2:


function doubleControlEvent() {
  if (event.key === 'Control') {
  	timesCtrlClicked++
    if (timesCtrlClicked >= 2) {
      console.log('Double control')
      // Double Crtl is clicked add your code here
    }
    setTimeout(() => (timesCtrlClicked = 0), 200)
  }  
}

let timesCtrlClicked = 0;
document.addEventListener('keyup', doubleControlEvent, true)


来源:https://stackoverflow.com/questions/1707650/detect-double-ctrl-keypress-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!