Javascript onkeyup 太"slow" ? .hide() 仅适用于 onkeydown



我正在使用一个函数来显示一个div:

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的问题是,在用键序列"cmd"打开命令行后,文本区显示"d"。

所以我不能关闭#cmd或者每次打开#cmd都会显示一个"d"

最后但并非最不重要的html代码:
<div id="cmd">
    <textarea id="cmdText" maxlength="80"></textarea>
</div>

也许你会知道解决我问题的方法!谢谢大家

现场演示

  • 您需要输入trim(),因为当您输入exit时,命令将存储exitn

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

}

相关内容

  • 没有找到相关文章

最新更新