Fade In String Characters with JQuery?

随声附和 提交于 2019-12-02 03:43:41

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/

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/

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!