分享一个应用在Vue项目中的自制简易控制台实现思路
这里只用jQuery记录一下思路,在项目中改造成Vue实现即可
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>简易控制台</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<style>
* {
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
}
#input-container {
width: 100%;
height: 100%;
background: #2e2f30;
cursor: text;
overflow: auto;
}
.input {
width: calc(100% - 50px);
height: 30px;
border: 0;
background: #2e2f30;
color: #fff;
}
.input:focus {
outline: 0;
}
.icon {
width: 30px;
height: 30px;
display: inline-block;
background: #2e2f30;
color: #fff;
text-align: center;
line-height: 30px;
}
</style>
</head>
<body>
<div id="input-container"></div>
<script>
(function () {
let $container = $(document.getElementById('input-container'))
let $elemnet = $(`<div class="icon">></div><input type="text" class="input">`)
$container.append($elemnet)
$container.find(".input:last").focus()
$container.on("keydown", function (event) {
// 监听回车键
if (event.key == "Enter") {
$container.find(".input").prop({
"readonly": true,
"autofocus": false
})
console.log($container.find(".input:last").val())
let $elemnet = $(`<div class="icon">></div><input type="text" class="input">`)
$container.append($elemnet)
$container.find(".input:last").focus()
}
// 监听退格键
if (event.key == "Backspace") {
if ($(".input:focus").val() == "") {
if ($container.find(".input").length > 1) {
$(".input:last").remove()
$(".icon:last").remove()
$container.find(".input:last").prop({
"readonly": false,
})
$container.find(".input:last").focus()
return false
}
}
}
})
// 鼠标点击任何位置都能获取焦点
$container.on("click", function () {
$container.find(".input:last").focus()
})
})()
</script>
</body>
</html>