【问题标题】:Javascript onkeyup too "slow"? .hide() works only with onkeydownJavascript onkeyup 太“慢”? .hide() 仅适用于 onkeydown
【发布时间】:2014-06-21 12:40:08
【问题描述】:

我正在使用一个函数来显示一个 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”打开命令行后,textarea 显示“d”。

所以我要么无法关闭#cmd,要么每次打开#cmd 时都会显示“d”。

最后但并非最不重要的html代码:

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

也许你会知道我的问题的解决方案!到目前为止谢谢你

【问题讨论】:

标签: javascript jquery html onkeydown onkeyup


【解决方案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;
    }

}

【讨论】:

  • 如果我改变一=二等的顺序,它就不再起作用了;但是 .trim();命令确实有帮助。现在一切都很好。非常感谢
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2015-07-21
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多