javascript - 按空格键后隐藏输入字段中的文本
问题描述
我想制作一个输入字段,一次只能看到一个单词。例如,如果用户想要输入“Hello world!” 在输入字段上,他们应该得到以下结果。
Typing 'Hello'
+-------------------------+
+Hello| +
+-------------------------+
Pressing space bar
+-------------------------+
+| +
+-------------------------+
Typing 'world!'
+-------------------------+
+world| +
+-------------------------+
- 按退格键时应该可以访问以前写的单词
After deleting 'world!' we should get 'Hello' again.
+-------------------------+
+Hello| +
+-------------------------+
- 这应该用纯 JavaScript 和 css 完成;jQuery 和其他库不是一个选项
这是一个模拟来演示所需的结果。
html
<div class="container">
<p> The desired output when a user starts typing</p>
<input type="text" id="simulateTyping">
<p> When a user presses space bar, they should get the effect shown above but in the same input field. </p>
<p> The previously written text should be accessible when pressing backspace</p>
<input type="text" id="myInput" placeholder="Start typing to see the effect" onkeypress="start()">
</div>
css
body {
text-align: center;
font-family: monospace;
}
.container {
margin: auto;
width: 500px;
border: 1px solid #eee;
font-size: 17px;
}
input {
width: 300px;
height: 40px;
font-family: inherit;
font-size: inherit;
}
JavaScript
var myInput = select('myInput');
var myOutput = select('simulateTyping');
var notStarted = true;
var typed;
Array.prototype.lastIndex = function () {
return this.length - 1;
}
function select(id) {
return document.getElementById(id)
}
function start() {
if (notStarted){
setInterval(theLoop, 100)
notStarted = false;
}
}
function theLoop() {
typed = myInput.value.split(/\s+/);
myOutput.value = typed[typed.lastIndex()]
}
解决方案
- 用于
"keyup"
给输入时间来更新它的值 - 使用标准
Event.key
读取插入的字符 - 用于
Array.prototype.pop()
从 Array 中移除并返回最后一项
const words = [];
const memorizer = (ev) => {
const inp = ev.target;
const val = inp.value.trim();
if(ev.key === ' ') {
const valSpl = val.split(' ');
words.push(valSpl[0]);
inp.value = valSpl[1] || '';
}
if(ev.key === 'Backspace' && val === '' ) {
inp.value = words.length ? words.pop() : '';
}
console.clear();console.log(words);
}
document.querySelector('#myInput').addEventListener('keyup', memorizer);
<input type="text" id="myInput" placeholder="Type, use space and backspace">
推荐阅读
- mysql - 如何自动化mysql复制数据库?
- javascript - 从 typescript 调用转义 url 中的特殊字符以到达 mvc 控制器
- aframe - 当我单击 a-frame 中的 VR 按钮时,我无法查看它
- arrays - 如何显示对象数组中的标题?
- azure - DataLake 锁定同一文件的读取和写入
- python - 使用 svgwrite 旋转路径
- python - 如何在 QTreeView 中获取当前选择的值我正在使用 StandardItemModel()
- excel - Powershell 使用 OLAP 查询刷新 Excel。凭证问题
- html - ngSubmit“myFunction 不是函数”打字稿,角度
- reactjs - Reactjs 无法设置样式