2013-05-19 40 views
0

我試圖讓Alt鍵設置快捷鍵爲Shift+Alt+ACtrl+Alt+A但是當`ShiftCtrl鍵被按下我不能確定Alt鍵是否被按下與否 。下面的代碼使問題更加清晰。爲什麼我無法按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")); 
    } 
    }; 

當我嘗試按一個鍵AltShiftCtrl鍵後e.altKey沒有得到真正的價值,我得到的結果作爲

shiftkey 
    shiftkey 
    shiftkey 
    shiftkey 
    shiftkey 
    shiftkey... 

或爲Ctrl

ctrlkey 
    ctrlkey 
    ctrlkey 
    ctrlkey 
    ctrlkey 
    ctrlkey 
    ctrlkey... 

回答

4

設計缺陷。您正在檢查是否按下了shiftKey。如果不是,那麼你檢查其他人。讓我們一步一步思考。

您先按下shift鍵。事件發生,你的第一個條件得到滿足。現在,當您按下alt鍵時,您的​​事件再次被調用,而這一次,由於您同時按住了shiftalt,因此會滿足第一個和第三個條件。 但是,程序從未達到第三個條件,因爲它在else子句中。這意味着只有你的第一個條件的代碼被評估,而其餘的條件會被跳過,因爲第一個條件是正確的。

更改您的設計以單獨檢查所有鑰匙,而不是每個鑰匙的else條款。

您的代碼應該是這樣的:

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")); 
} 
}; 

覺得這個例子,讓您更清楚的缺陷:

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

你可以看到,沒關係,第二條件是否爲真或者不是,只要第一個是。

在你的情況下,儘管使用邏輯運算符&&會更有意義,因爲只有在按住所有三個鍵來創建快捷方式時你纔想做點什麼。這會讓你的代碼如下:

if(e.shiftKey && e.altKey && e.keyCode === 65){ 
    console.log('Shortcut active'); 
} 
相關問題