2014-06-21 23 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