简体   繁体   English

JavaScript 打字机退格效果

[英]JavaScript typewriter backspace effect

I got this code from w3s https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter and I can't figure out how to backspace letters after its done typing.我从 w3s https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter得到了这个代码,我不知道如何在完成输入后退格字母。 I've tried to decrement I but that didn't work either.我试图减少 I 但这也不起作用。 Also, how can I add a delay so the backspace effect doesn't start immediately after?另外,如何添加延迟以便退格效果不会立即开始?

 var i = 0; var txt = 'Lorem ipsum dummy text blabla.'; var speed = 50; function typeWriter() { if (i < txt.length) { document.getElementById("demo").innerHTML += txt.charAt(i); i++; setTimeout(typeWriter, speed); } if(i >= txt.length){ document.getElementById("demo").innerHTML -= txt.charAt(i); i--; setTimeout(typeWriter, speed); } }
 <!DOCTYPE html> <html> <body> <h1>Typewriter</h1> <button onclick="typeWriter()">Click me</button> <p id="demo"></p> </body> </html>

You can use a boolean value (true or false) to keep track if you are backspacing or not.您可以使用boolean值(true 或 false)来跟踪是否退格。 If you are not, you want to increment i if you are backspacing then you want to decrement i .如果你不是,你想增加i如果你退格然后你想减少i Here I have used .substring to get a portion of the string from index 0 up to a given index.在这里,我使用.substring来获取从索引 0 到给定索引的字符串的一部分。

See example below:请参阅下面的示例:

 var i = 0; var txt = 'Lorem ipsum dummy text blabla.'; var speed = 50; var backspace = false; var outputElem = document.getElementById("demo"); // get element when page loads function typeWriter() { outputElem.textContent = txt.substring(0, i); if (i > txt.length) backspace = true; if (i == 0) backspace = false; i = i + (backspace ? -1 : 1); setTimeout(typeWriter, speed); }
 <h1>Typewriter</h1> <button onclick="typeWriter()">Click me</button> <p id="demo"></p>

If you want to stop the loop completely (after the backspace) you can add a condition to the setTimeout function call.如果您想完全停止循环(在退格之后),您可以向setTimeout函数调用添加条件。 Moreover, you can give a delay between the typing and the backspacing:此外,您可以在打字和退格之间设置delay

 var i = 0; var txt = 'Lorem ipsum dummy text blabla.'; var speed = 50; let delay = 25; var backspace = false; var outputElem = document.getElementById("demo"); function typeWriter() { outputElem.textContent = txt.substring(0, i); if (i > txt.length + delay) backspace = true; if (i == -1) backspace = false; i = i + (backspace ? -1 : 1); if(i != -1) setTimeout(typeWriter, speed); }
 <h1>Typewriter</h1> <button onclick="typeWriter()">Click me</button> <p id="demo"></p>

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

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