How to detect: Press twice the same key, but hold it the second time for 2 seconds

為{幸葍}努か 提交于 2019-12-11 03:14:39

问题


How to detect: Press twice the same key, but hold it the second time for 2 seconds ?

I'm looking for an efficient way to detect a keydown event for the keycode 37 (left arrow) (or any other key when necessary) and then a second keydown of the same keycode for 1.5 or 2 seconds just after releasing the key, Within a given delay, like 1 second.

This is to go back without confusing between "Go back, on the previous page" (this is what i want to do) and "Go on the element before this one, on the same page"

I already tried with old_keycode and old_keycode_timepressed and new_keycode new_keycode_timepressed in the $(document.ready() tag, but I need to copy/paste the entire code for each keycode i want, and the code itself isn't efficient.

Anyone have heard of a plugin that can help me with that, or anyone is willing to help me whit it?

Thanks for your time.


回答1:


jsFiddle demo

var twice_37 = 0;

$(document).on('keyup', function( e ){

  if(e.which===37){         // If left arrow    

    if(twice_37===1){       // (remember that twice_37 is 0 initially)
      alert('Do something! (you pressed Left twice!)');
    }

    twice_37 = 1;          // Set to 1 and...
    setTimeout(function(){ // ...reset to 0 after 1s
      twice_37 = 0; 
    }, 1000);

  }

});


来源:https://stackoverflow.com/questions/16454375/how-to-detect-press-twice-the-same-key-but-hold-it-the-second-time-for-2-secon

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