开发者

Detecting combined keystroke in JavaScript

开发者 https://www.devze.com 2023-02-16 01:22 出处:网络
I am creating a html page which contains a question (a puzzle like situation ). The answer for the question is "Windows 7", but I want the user to get through the question only if hepresses

I am creating a html page which contains a question (a puzzle like situation ). The answer for the question is "Windows 7", but I want the user to get through the question only if he presses windows key followed by 7. I want to create a JavaScript function for this. I am able to capture the individual key press by getting the开发者_如何学Go ASCII value of the keystroke., but when I try to do it in combination its not working. How to go about solving this? Any ideas?


http://jsfiddle.net/loktar/MsNPW/5/

var keys = [];

document.onkeydown = function(evt){    
   var key = evt.keyCode;
   keys[key] = true;
    if(keys[91] && keys[55]){
       console.log("win7");
    } 
}

document.onkeyup = function(evt){    
   var key = evt.keyCode;
   keys[key] = false;
}


You can detect keydown and keyup events, and keep a list of keys that have been pressed. Add the key to the list on keydown, and remove them from the list on keyup. From there you can just check the list at appropriate times (e.g. at the end of the keydown event).

Remember that each keypress is it's own unique event. Multiple keys being pushed aren't naturally related, so that's why you need to create this list yourself.

I suggest you use a library like jQuery, and there may be plugins which can help. That said, the general concept I described shouldn't be too tough to implement yourself. Let me know if pseudocode would help clarify the algorithm I'm describing.

0

精彩评论

暂无评论...
验证码 换一张
取 消