在 Jquery 中模拟 'backspace'

Simulate 'backspace' in Jquery

我有一个简单的动画代码,看起来像控制台输入。

最初来自:https://codepen.io/atunnecliffe/pen/BaZyLR

我将启动画面介绍修改为我网站中的控制台输入:

代码:

<script>
        //console
        var textarea = $('.term');
        var text = 'ping life';

        var i = 0;

        runner();

        function runner() {
            textarea.append(text.charAt(i));
            i++;
            setTimeout(
                function () {
                    runner();
                }, Math.floor(Math.random() * 1000) + 50);
        }
    </script>

现在我想要的效果有点复杂,至少对我来说是这样,因为我对 JQuery 的了解是有限的。我希望代码输入 ping life,然后完全退格,无限重复。我查看了如何使用 (8) 的转义序列在 JQuery 中模拟退格键,但我不确定如何使用转义序列,也不知道如何将函数实现到现有的递归函数中,让它无限重复.

任何帮助都会很棒 :)

像这样? 像这样计数会产生类似计数模式的锯齿形。我为输入的开始和结束添加了缓冲区,并为删除字母添加了固定超时。

textarea.text(text.substr(0, i)) 选择文本的子字符串(视为字母数组 - 选择索引 0 和 i 之间的所有内容)

比添加和删除字母更容易

var direction = 1;
var i = 0;
var textarea = $('.term');
var text = 'ping life';

// NOTE:
// I added the "@dev:~$ " as css:before elem, easier to write the code

function count() {
    i += direction;
    direction *= (((i % text.length) == 0) ? -1 : 1);
    textarea.text(text.substr(0, i));
    clearInterval(time);
    
    // direction is 1 if counting up
    if (direction === 1) {
        if (i === 0) {
            // buffer for start
            time = setInterval(count, 1000);
        } else {
            time = setInterval(count, Math.floor(Math.random() * 1000) + 50);
        }
    } else {
        // direction is -1 if counting down
        if (i === text.length) {
            time = setInterval(count, 1500);
        } else {
            // buffer for end
            time = setInterval(count, 100);
        }
    }
   
}

// inital interval
// setTimeout doesn't work well here
var time = setInterval(count, 1000)
html,
body {
  margin: 0 auto;
  height: 100%;
}

pre {
  padding: 0;
  margin: 0;
}

pre::before {
  content: "@dev:~$ ";
  color: white;
}

.load {
  margin: 0 auto;
  min-height: 100%;
  width: 100%;
  background: black;
}

.term {
  font-family: monospace;
  color: #fff;
  opacity: 0.8;
  font-size: 2em;
  overflow-y: auto;
  overflow-x: hidden;
  padding-top: 10px;
  padding-left: 20px;
}

.term:after {
  content: "_";
  opacity: 1;
  animation: cursor 1s infinite;
}

@keyframes cursor {
  0% {
    opacity: 0;
  }
  40% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="load">
  <pre class="term"></pre>
</div>