2014-06-21 21 views
1

我用一個函數來顯示一個div:Javascript onkeyup太「慢」? .hide()只能與onkeydown事件

function showCMD() { 
$("#cmd").show("fast"); 
$('#cmdText').focus(); 
} 

出現這種情況,如果用戶鍵入「CMD」他的鍵盤上。

主要代碼:

document.onkeyup = function(event) { 

     //Save the last three keys 
     one = two; 
     two = three;   
     three = event.keyCode; 

     if (one == 67 && two == 77 && three == 68 && cmdOpen == false) { 
     showCMD(); 
     } 
      //if the pressed key is ENTER and the textarea is focused 
      if (event.keyCode == 13 && $("#cmdText").is(":focus") == true) { 
       //passing the code to another function 
       execCMD(document.getElementById("cmdText").value); 

       //empty the textarea - works great 
       document.getElementById("cmdText").value = ""; 
       return false; 
      } 

    } 

代碼鍵入用戶將在這裏處理:

function execCMD(command) { 

    if(command == "exit") $("#cmd").hide("fast"); 
    console.log(command); 
} 

控制檯給我每次退出。但它不會隱藏div #cmd。 如果我將onkeyup更改爲onkeydown,它工作正常。 onkeydown的問題在於textarea在用鍵序列「cmd」打開命令行後顯示「d」。

因此,無論我何時無法關閉#cmd,或者每次打開#cmd時都顯示「d」。

最後但並非最不重要的HTML代碼:

<div id="cmd"> 
    <textarea id="cmdText" maxlength="80"></textarea> 
</div> 

也許你會知道我的問題的解決方案!謝謝到目前爲止

+0

你也應該謹慎使用 '==',而使用 '===',以避免類型轉換。看到這篇文章:http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons –

回答

1

Live demo

  • 您需要trim()命令,因爲當你鍵入exit,該命令將存儲exit\n

JS

function execCMD(command) { 
    if(command.trim() == "exit") // Add trim() 
     $("#cmd").hide("fast"); 
    console.log(command); 
} 

function showCMD() { 
    $("#cmd").show("fast"); 
    $('#cmdText').focus(); 
} 

document.onkeyup = function(event) { 

    //Save the last three keys 
    one = two; 
    two = three; 
    three = event.keyCode; // Change the order of declaration and definition 


    if (one == 67 && two == 77 && three == 68 && cmdOpen == false) { 
    showCMD(); 
    } 

    //if the pressed key is ENTER and the textarea is focused 
    if (event.keyCode == 13 && $("#cmdText").is(":focus") == true) { 
     //passing the code to another function 
     execCMD(document.getElementById("cmdText").value); 

     //empty the textarea - works great 
     document.getElementById("cmdText").value = ""; 
     return false; 
    } 

}

+1

如果我改變了一個=二它不再工作了;但.trim();命令確實有幫助。現在一切都很好。非常感謝你 – wernersbacher