在系统控制台界面、比如windows的cmd窗口,我们常常会按下上键来重复使用一些命令。
其实一般的软件也有这种需要,比如说网页聊天中我想要重复发一句话刷屏,那么如何在html代码中简单的实现这个功能呢?
直接上代码:
<input id="msgContent" name="msgContent" onkeydown="keyDown(event)" placeholder="请输入消息">
var historyIndex = 0;
var historyStack=[];
function keyDown(event) {
if(event.keyCode==13){sendMsg();}
if(event.keyCode==38){// up arrow
historyIndex--;
let historyContent = historyStack.slice(historyIndex)[0];
if(historyContent){
$('#msgContent').val(historyContent);
}
}
if(event.keyCode==40){// dw arrow
historyIndex++;
let historyContent = historyStack.slice(historyIndex)[0];
if(historyIndex<0 && historyContent){
$('#msgContent').val(historyContent);
}
}
}
function sendMsg() {
// 这里会有发送请求之类的代码
historyStack.push(input);
historyIndex = 0;
$("#msgContent").val('');
}