Show text letter by letter

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

    You really should just append, or show/hide.

    However, if for some odd reason you don't want to alter your text, you can use this overly-complicated-for-no-good-reason piece of code:

    HTML:

    I'm moving slowly...

    CSS:

    p {
        font-family: monospace;
        float: left;
        padding: 0;
        position: relative;
    }
    .cover {
        height: 100%;
        width: 100%;
        background: #fff;
        position: absolute;
        top: 0;
        right: 0;
    }
    

    jQuery:

    var $p = $('p'),
        $cover = $('.cover'),
        width = $p.width(),
        decrement = width / $p.text().length;
    
    function addChar()
    {        
        $cover.css('width', '-=' + decrement);
    
        if ( parseInt( $cover.css('width') ) < width )
        {
            setTimeout(addChar, 300);
        }
    }
    
    addChar();
    

    And finally, here's the fiddle: http://jsfiddle.net/dDGVH/236/

    But, seriously, don't use this...

提交回复
热议问题