我正在使用一个函数来显示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>
也许你会知道我的问题的解决方案!谢谢你到目前为止
答案 0 :(得分:1)
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;
}
}