gpt4 book ai didi

javascript - 按空格键后隐藏输入字段中的文本

转载 作者:行者123 更新时间:2023-11-30 10:58:27 24 4
gpt4 key购买 nike

我想制作一个一次只能看到一个单词的输入框。例如,如果用户想要键入“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() 删除并返回数组中的最后一项

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">

关于javascript - 按空格键后隐藏输入字段中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com