最近我开始使用jQuery,并学习了一些教程。现在我觉得我可以稍微胜任使用它(这非常简单),我认为如果我能够在我的网页上制作一个“控制台”(就像在FPS游戏中那样,你按下“键”),然后让它自己Ajax回服务器,以便做一些事情,那将会很酷。
我最初认为最好的方法是只获得文本区域内的文本,然后分割它,或者我应该使用keyup事件,将键码转换为ASCII字符,将字符附加到字符串并将字符串发送到服务器(然后清空字符串)。
我找不到任何关于从文本区域获取文本的信息,我得到的只是按键信息。另外,如何将键码转换为ASCII字符?
读取textarea值和代码-字符转换:
功能键(e) {
味精。innerHTML = '最后一个键:${String.fromCharCode(e.c ycode)} '
如果(e。key == 'Enter') {
Console.log ('send: ', mycon.value);
mycon.value = ";
e.preventDefault ();
}
}
按enter键'send'<br>
<textarea id='mycon' onkeydown="keys(event) "" > < / >文本区域
< div id = "味精" > < / div >
下面是像《雷神之锤》一样的主机版本,只在潜水版:)
document.addEventListener('keyup', keys);
let conShow = false
function keys(e) {
if (e.code == 'Backquote') {
conShow = !conShow;
mycon.classList.toggle("showcon");
} else {
if (conShow) {
if (e.code == "Enter") {
conTextOld.innerHTML+= '<br>' + conText.innerHTML;
let command=conText.innerHTML.replace(/ /g,' ');
conText.innerHTML='';
console.log('Send to server:', command);
}
else if (e.code == "Backspace") {
conText.innerHTML = conText.innerText.slice(0, -1);
} else if (e.code == "Space") {
conText.innerHTML = conText.innerText + ' '
} else {
conText.innerHTML = conText.innerText + e.key;
}
}
}
}
body {
margin: 0
}
.con {
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-start;
width: 100%;
height: 90px;
background: rgba(255, 0, 0, 0.4);
position: fixed;
top: -90px;
transition: top 0.5s ease-out 0.2s;
font-family: monospace;
}
.showcon {
top: 0px;
}
.conTextOld {
color: white;
}
.line {
display: flex;
flex-direction: row;
}
.conText{ color: yellow; }
.carret {
height: 20px;
width: 10px;
background: red;
margin-left: 1px;
}
.start { color: red; margin-right: 2px}
Click here and Press tilde ` (and Enter for "send")
<div id="mycon" class="con">
<div id='conTextOld' class='conTextOld'>Hello!</div>
<div class="line">
<div class='start'> > </div>
<div id='conText' class="conText"></div>
<div class='carret'></div>
</div>
</div>