简体   繁体   English

JavaScript中如何实现暂停和删除打字机效果?

[英]How to implement pause and delete typewriter effect in JavaScript?

new to JS here and was wondering if someone could guide me on how I can pause and delete when implementing a typewriter effect in JavaScript.这里是 JS 的新手,想知道是否有人可以指导我在 JavaScript 中实现打字机效果时如何暂停和删除。 I've got a function that successfully types out each word in an array, however I would like it to pause after typing each word and backspace or delete the letters before typing the next one.我有一个 function 可以成功键入数组中的每个单词,但是我希望它在键入每个单词和退格后暂停或在键入下一个单词之前删除字母。

 //counter var i = 0; var index = 0; var texts = ['Salesforce Consultant', 'Developer', 'Writer']; var speed = 110; let letter = ''; let currentText = ''; let delay = 25; function typeWriter() { //If counter is less than the # of letters in txt, reset array of words if (i === texts.length) { i = 0; } //Use count to select text to display currentText = texts[i]; letter = currentText.slice(0, ++index); document.querySelector("#demo").textContent = letter; //If letters displayed are the same number of letters in the current text if (letter.length === currentText.length) { //Pause before deleting //Delete letters in word //Word is done displaying, and reset letters on screen i++; index = 0; } setTimeout(typeWriter, speed); } typeWriter();
 <div id="demo"></div>

HTML HTML

    <div class="centered">
    <div class="intro">
        <p>A &thinsp;</p> 
        <p class ="typing" id="demo"></p>
    </div>
</div>

You can do this by introducing a variable that determines how the index will change (+1 or -1).您可以通过引入一个变量来确定index将如何变化(+1 或 -1)。 The different delay is just a different argument to setTimeout .不同的延迟只是setTimeout的不同参数。

I would also suggest converting some global variables into function parameters: that way they are better (more narrowly) scoped.我还建议将一些全局变量转换为 function 参数:这样它们的范围更好(更窄)。 The change that these variables get, can be managed by what you let setTimeout pass on to the next call.这些变量获得的更改可以通过您让setTimeout传递给下一次调用的内容来管理。

Here is how that could work:这是如何工作的:

 const texts = ['Salesforce Consultant', 'Developer', 'Writer']; const speed = 110; const pause = 800; // <--- the longer delay between text direction changes function typeWriter(i=0, index=1, direction=1) { let displayed = texts[i].slice(0, index); document.querySelector("#demo").textContent = displayed; if (displayed.length >= texts[i].length) { // start removing after pause setTimeout(() => typeWriter(i, index-1, -1), pause); } else if (displayed.length === 0) { // go to next text after pause setTimeout(() => typeWriter((i+1) % texts.length), pause); } else { // continue in the current direction setTimeout(() => typeWriter(i, index+direction, direction), speed); } } typeWriter();
 <div id="demo"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM