问题
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