首页 > 解决方案 > 按空格键后隐藏输入字段中的文本

问题描述

我想制作一个输入字段,一次只能看到一个单词。例如,如果用户想要输入“Hello world!” 在输入字段上,他们应该得到以下结果。

Typing 'Hello'

+-------------------------+
+Hello|                   + 
+-------------------------+

Pressing space bar
+-------------------------+
+|                        + 
+-------------------------+

Typing 'world!'
+-------------------------+
+world|                   + 
+-------------------------+
After deleting 'world!' we should get 'Hello' again.
+-------------------------+
+Hello|                   + 
+-------------------------+

这是一个模拟来演示所需的结果。

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()]
    }

标签: javascripthtmlcss

解决方案


  • 用于"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">


推荐阅读