Fade In String Characters with JQuery?

前端 未结 3 1388
耶瑟儿~
耶瑟儿~ 2021-01-25 18:26

Here is my code. For some reason the entire String fades in at one time instead of each individual character. My console.log shows the characters are being executed one by one.

相关标签:
3条回答
  • 2021-01-25 18:46

    I thought about this for a bit, and believe this would be better served with $.Deferred() This allows the animation to be whatever you want, and if you change that, it does not impact the rest - the animation controls the timing, firing "done" and starting the next letter when it completes by triggering the custom event.

    Nothing fancy, just does what you asked.

    Simple markup:

    <div id="animator"></div>
    

    For example:

    var myString = " Freddy The Mark";
    var i = 0;  // used to iterate the string, could be done other ways
    var myEffect = function (c) {
        return $("#animator").append(c).fadeIn(800).delay(800).fadeOut(1);
    };
    $("#animator").on("show", function () {
        var c = myString[i];
        $.when(myEffect(c)).done(function () {
            i++;
            if (i < myString.length) {
                $('#animator').trigger('show');
            } else {
                $("#animator").show();//show it when we are done
            }
        });
    });
    $('#animator').trigger('show'); //get started by firing the custom event handler
    

    Put it all together in a sample: http://jsfiddle.net/N8eRN/1/

    0 讨论(0)
  • 2021-01-25 18:53

    To get the individual letters to fade in, they need to be DOM elements.

    $(function() {
      var string = " David";
      var q = jQuery.map(string.split(''), function (letter) {
        return $('<span>'+letter+'</span>');
      });
    
      var dest = $('#fadeIn');
    
      var c = 0;
      var i = setInterval(function () {
        q[c].appendTo(dest).hide().fadeIn(1000);
        c += 1;
        if (c >= q.length) clearInterval(i);
      }, 1000);
    
    });
    

    http://jsfiddle.net/bGsa3/5/

    0 讨论(0)
  • 2021-01-25 19:03

    The for loop is executing the delay, append and fade in on all letters at once, so they will show at the same time. You want to do this with a setInterval instead:

    var string = "David",
    stringCount = 0;
    
    setInterval(function(){
      $('#fadeIn').append(string[stringCount]);
      stringCount += 1;
    },1000);
    

    Working fiddle: http://jsfiddle.net/bGsa3/

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