0

AltショートカットをShift+Alt+Aorに設定するキーを取得しようとしていますCtrl+Alt+Aが、`ShiftorCtrlキーが押されたときに、キーが押されたかどうかを判断できませAltん。次のコードは、問題をより明確にします。

    el.onkeydown=function(e){
    //alert(e.keyCode);

    if(e.shiftKey==true){
    document.body.appendChild(document.createTextNode("shiftkey"));
    document.body.appendChild(document.createElement("br"));
    }
    else if(e.ctrlKey==true){
    document.body.appendChild(document.createTextNode("ctrlkey"));
    document.body.appendChild(document.createElement("br"));
    }
    else if(e.altKey==true){
    document.body.appendChild(document.createTextNode("altkey"));
    document.body.appendChild(document.createElement("br"));
    }
    };

またはキーのAlt後にキーを押そうとすると、 true の値が得られず、次のような結果が得られますShiftCtrle.altKey

    shiftkey
    shiftkey
    shiftkey
    shiftkey
    shiftkey
    shiftkey...

またはのためにCtrl

    ctrlkey
    ctrlkey
    ctrlkey
    ctrlkey
    ctrlkey
    ctrlkey
    ctrlkey...
4

1 に答える 1

4

Design flaw. You're checking if the shiftKey is pressed down. If it isn't, then you check for the others. Let's think of it step by step.

You press the shift key first. Event fires, and your first condition is satisfied. Now, when you press down the alt key, your keydown event is called again, and this time, since you're holding down both shift and alt, the first and third conditions are met. However, the program never gets to the third condition, because it's in an else clause. Which means only your first condition's code is evaluated, and the rest of the conditons are skipped, since the first was true.

Change your design to check for all the keys individually, not with else clauses for each.

Your code would look like this:

el.onkeydown=function(e){
//alert(e.keyCode);

if(e.shiftKey==true){
document.body.appendChild(document.createTextNode("shiftkey"));
document.body.appendChild(document.createElement("br"));
}
if(e.ctrlKey==true){
document.body.appendChild(document.createTextNode("ctrlkey"));
document.body.appendChild(document.createElement("br"));
}
if(e.altKey==true){
document.body.appendChild(document.createTextNode("altkey"));
document.body.appendChild(document.createElement("br"));
}
};

Think of this example to make your flaw clearer:

if(true){
    console.log('First');
}
else if(true){
    console.log('Second');
}

You can see that it doesn't matter whether the second condition is true or not, as long as the first is.

In your case, though, using the && logical operator would make more sense, since you only want to do something when all three keys are held down to create a shortcut. That'd make your code like this:

if(e.shiftKey && e.altKey && e.keyCode === 65){
    console.log('Shortcut active');
}
于 2013-05-19T15:43:43.277 に答える