问题
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 ascii value of the keystroke. But when I try to do it combinedly its not working. How to go about solving this.. any ideas..
回答1:
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;
}
回答2:
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.
来源:https://stackoverflow.com/questions/5235789/detecting-combined-keystroke-in-javascript