Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
escribiendo animación en cada elemento con su clase

Estoy tratando de hacer una animación de escritura pero no funciona y no sé por qué. Sé que podría hacerlo en CSS pero me gustaría probarlo en JS. El problema es probablemente con la función en sí. No soy el mejor en JS.

 <p class="typing-animation">this will be animated</p> <p class="typing-animation">this aswell</p> <script> const sleep = (ms) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; const toType = document.getElementsByClassName("typing-animation"); document.getElementsByClassName("typing-animation").textContent = ""; (async (toType) => { for (let each of toType) { text = each.textContent; each.textContent = ""; let i = 0; for (let every of text) { every.textContent += text[i]; await sleep(200); i++; } } })(toType); </script>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Tu estás en el camino correcto. Acabo de limpiar un poco las cosas para facilitar la lectura.

Aquí hay una caja de códigos: https://codesandbox.io/s/typing-animation-kdn8v

Supuse que desea que las animaciones sucedan en paralelo. Por esta razón, queremos ejecutar cada elemento HTML y llamar a nuestra función animateType en cada uno de ellos sin ninguna espera.

Cada llamada de animateType significa que hay una copia de esta función ejecutándose para este elemento HTML. De esta forma, las variables como text dentro de la función no se mezclan entre los elementos HTML. Esto se llama un "cierre". Todas las variables dentro de esa "instancia" de la función, viven solo dentro de esa instancia de la función.

Almacenamos el texto original, luego borramos el contenido del elemento HTML, luego, al igual que usted, hacemos un bucle con las letras del texto almacenado en caché y agregamos cada una al elemento HTML.

 // Stackoverflow: https://stackoverflow.com/questions/70573442/typing-animation-on-each-element-with-its-class const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const clearAndCache = (elements) => { let cachedText = []; for (let element of elements) { cachedText.push(element.textContent); element.textContent = ""; } return cachedText; }; const animateTypeSync = async (typeables, ms) => { const cachedText = clearAndCache(typeables); for (let i = 0; i < typeables.length; i++) { for (let character of cachedText[i]) { typeables[i].textContent += character; await sleep(ms); } } }; const animateTypeAsync = (typeables, ms) => { const cachedText = clearAndCache(typeables); Array.from(typeables).forEach(async (element, i) => { for (let character of cachedText[i]) { element.textContent += character; await sleep(ms); } }); }; const elementsSync = document.getElementsByClassName("typing-animation-sync"); animateTypeSync(elementsSync, 200); const elementsAsync = document.getElementsByClassName("typing-animation"); animateTypeAsync(elementsAsync, 150);
 <!DOCTYPE html> <html> <head> <title>Typing Animation</title> <meta charset="UTF-8" /> </head> <body> <h1>Typing Animations</h1> <div style="width: 100%; display: inline-flex;"> <div style="width: 50%;"> <h2>Async</h2> <p class="typing-animation">These will run</p> <p class="typing-animation">at the same time</p> </div> <div style="width: 50%;"> <h2>Sync</h2> <p class="typing-animation-sync">These will animate</p> <p class="typing-animation-sync">one at a time</p> </div> </div> </body> <script src="src/index.js"></script> </html>

Editar: se agregó la versión de sincronización al código después del comentario de OP.

about 4 years ago · Juan Pablo Isaza Report

0

¿Creo que esto es lo que buscas?

 <p class="typing-animation">this will be animated</p> <p class="typing-animation">this aswell</p> <script> const sleep = (ms) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; // This is an array of html elements, since getElementsByClassName returns an array, since there can be more than one html element with that class. const elements = document.getElementsByClassName("typing-animation"); (async (typedElements) => { let texts = [] for (let element of typedElements){ // The property to access the text inside the elements .innerHTML, if its a user interactuable element such as <input> or <textarea> then its .value texts.push(element.innerHTML); element.innerHTML = ""; } // texts and typedElements has the same length. for (let i = 0; i < texts.length; i++) { for (let character of texts[i]) { typedElements[i].innerHTML += character; await sleep(200) } } })(elements); </script>

Si desea ese efecto en varios lugares y más fácil de implementar, hay una biblioteca que ya lo hace, más fácil de personalizar y usar: Typed.js

 <span class="typed"></span> <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12"></script> <script> // For more examples check: https://github.com/mattboldt/typed.js // Full docs at: https://mattboldt.github.io/typed.js/docs/ const options = { strings: ['This will be typed!', 'This too! ^500 <br> And this will go under!'], typeSpeed: 40, backSpeed: 40, backDelay: 2000, }; // We'll bind the typing animation to the .typed class. let typed = new Typed('.typed', options); </script>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!