Show text letter by letter

前端 未结 16 1548
旧巷少年郎
旧巷少年郎 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:05

    When I did this I ran into the problem of a word jumping from the end of one line to the begging of the next as it the letters appeared to get around this I used to side by side spans, one of which the text was transparent, the other visible and simply moved letters one by one from the invisible span to the visible. Here's a fiddle.

    HTML

    CSS

    .visible {
      color: black;
    } 
    
    .invisible {
      color: transparent;
    }
    

    JS

    var text = "Whatever you want your text to be here",
        soFar = "";
    
    var visible = document.querySelector(".visible"),
        invisible = document.querySelector(".invisible");
    
    invisible.innerHTML = text;
    var t = setInterval(function(){
      soFar += text.substr(0, 1),
      text = text.substr(1);
    
      visible.innerHTML = soFar;
      invisible.innerHTML = text;
    
      if (text.length === 0) clearInterval(t);
    }, 100)
    

提交回复
热议问题