Typewriter Effect with jQuery

后端 未结 2 1307
[愿得一人]
[愿得一人] 2020-11-27 18:13

Edit: I didn\'t really ask all the questions I should have asked in my original question. To help make this easier for people looking for a similar answer, this is what

2条回答
  •  旧时难觅i
    2020-11-27 18:37

    Added a simple function at the end, and a few variables in between...

    Fiddle

    var where, when; //added
    
    $.fn.teletype = function(opts){
        var $this = this,
            defaults = {
                animDelay: 50
            },
            settings = $.extend(defaults, opts);
    
        var letters = settings.text.length; //added
    
        where = '#' + $($this).attr('id'); //added
        when = settings.animDelay; //added
    
        $.each(settings.text, function(i, letter){
            setTimeout(function(){
                $this.html($this.html() + letter);
    
                if( $($this).html().length == letters ){ reverse(); } // Added to trigger reversing function
    
            }, settings.animDelay * i);
        });
    };
    
    $(function(){
        $('#container').teletype({
            animDelay: 100,
            text: 'Now is the time for all good men to come to the aid of their country...'
        });
    });
    
    
    // Added Reversing Function
    
        function reverse(){
    
            if ($(where).html().length > 0){          
                x = $(where).html().length - 1;
                y = $(where).html().substr(0, x);
                $(where).html(y);
                setTimeout(reverse , when);
            }else{
                console.log('Reverse Complete');
                clearTimeout(reverse);
            }
        }
    

提交回复
热议问题