jQuery text effect where words appear one by one

跟風遠走 提交于 2019-11-29 04:26:14

Working example: http://jsfiddle.net/TcdQb/

var str = $('span.ticker').text();

var spans = '<span>' + str.split(/\s+/).join(' </span><span>') + '</span>';

$(spans).hide().appendTo('body').each(function(i) {
    $(this).delay(1000 * i).fadeIn();
});
  • This places the words in span tags: "<span>Happy </span><span>New </span><span>Year </span><span>2011</span>"

  • Creates DOM elements: $(spans)

  • Hides them: .hide()

  • Appends them: .appendTo('body')

  • Finally, iterates over them using .each(), and .delay() the .fadeIn() of each one by 1000ms multiplied by the current index of the iteration.


EDIT: Here's an update to the example that uses a shorter delay, and a longer animation, so the animations overlap a little.

http://jsfiddle.net/TcdQb/1/

    $(this).delay(400 * i).fadeIn(1000);

EDIT: To deal with nested tags (one level deep only) you could do this:

http://jsfiddle.net/WgMrz/

var h1 = $('div#greeting h1');

h1.hide().contents().each(function() {
    var words;
    if (this.nodeType === 3) {
        words = '<span> ' + this.data.split(/\s+/).join(' </span><span> ') + ' </span>';
        $(this).replaceWith(words);
    } else if (this.nodeType === 1) {
        this.innerHTML = '<span> ' + this.innerHTML.split(/\s+/).join(' </span><span> ') + ' </span>';
    }
});

   // Remove any empty spans that were added
h1.find('span').hide().each(function() {
    if( !$.trim(this.innerHTML) ) {
        $(this).remove();
    }
});

h1.show().find('span').each(function(i) {
    $(this).delay(400 * i).fadeIn(600);
});

I'm not an expert, but maybe you're overthinking this. How about:

   var fadeWordsIn = function(elem$) {
      var txt = elem$.text().split(' ');
      elem$.empty();
      var pushIt = function() {
          if (txt.length) {
              var word = txt.shift();
              var span$ = $("<span>" + word + " </span>");
              elem$.append(span$);
              span$.hide().fadeIn(1000, pushIt);
          }
       };
       pushIt();
  };

You want the "BlockFadeIn by word" animation here: http://dev.seankoole.com/jquery/ui-effect/text.html

Just released!

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