Show text letter by letter

前端 未结 16 1454
旧巷少年郎
旧巷少年郎 2020-11-27 16:38

What is the most elegant way of showing an html text letter by letter (like videogame captions) using CSS and JavaScript?

While I\'m sure that his can be solved usin

相关标签:
16条回答
  • 2020-11-27 17:18

    Vanillla

    (function () {
    
    var showText = function(target, msg, index, interval){
    
      var el = document.getElementById(target);
    
      if(index < msg.length){
        el.innerHTML = el.innerHTML + msg.charAt(index);
        index = index + 1;
        setTimeout(function(){
          showText(target,msg,index,interval);
        },interval);
      }
    
    };
    
    
    showText("id", "Hello, World!", 0, 50);   
    
    })();
    

    you could improve on this code by changing it so you only get the el one time due to the fact that it takes a bit of resources to modify the DOM.

    0 讨论(0)
  • 2020-11-27 17:23

    I made a tiny jquery plugin for that. First you need to make sure that the text will be visible if javascript is disabled, and if not, redisplay the text letter by letter.

    $.fn.retype = function(delay) {
        var el = this,
            t = el.text(),
            c = t.split(''),
            l = c.length,
            i = 0;
        delay = delay || 100;
        el.empty();
        var interval = setInterval(function(){
            if(i < l) el.text(el.text() + c[i++]); 
            else clearInterval(interval);
        }, delay);
    };
    

    Usage will be just as easy as this:

    $('h1').retype();
    
    0 讨论(0)
  • 2020-11-27 17:24
    function textRoll(message, interval){
       setTimeout(() => {
             para.innerHTML += message.charAt(0);
             return textRoll(message.slice(1))
       }, interval)
    }
    
    0 讨论(0)
  • 2020-11-27 17:25

    You need to wrap each letter in span tag, because anonymous html elements cannot be styled. Then reveal one span at a time. This avoids some innerText / innerHTML issues (no DOM reflow?) but can be overkill in your case.

    0 讨论(0)
提交回复
热议问题