Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

javascript - fading a paragraph in word by word using jquery?

    <p class="example">i want to split this paragraph into 
words and fade them in one by one</p>

the jquery/js:

$(document).ready(function() {

    var $txt = $(".example")
       ,$words = $txt.text()
       ,$splitWords = $words.split(" ");

    $txt.hide();

    for(i = 0; i < $splitWords.length; i++){
     // i want fade in each $splitWords[i]
     //$splitWords[i].fadeIn(....  - i tried this doesnt work

   }
  });

im trying to split the paragraph into words, and fade them in one by one, thier might be an easier way to do this without splitting the words, please shed some light on this. thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Text by itself can't have an opacity, therefore you must wrap the text with an element that can have opacity (such as a span). You can then fade in those spans.

Try this:

http://jsfiddle.net/6czap/

var $el = $(".example:first"), text = $el.text(),
    words = text.split(" "), html = "";

for (var i = 0; i < words.length; i++) {
    html += "<span>" + words[i] + " </span>";
}

$el.html(html).children().hide().each(function(i){
  $(this).delay(i*500).fadeIn(700);
});

Update for benekastah: http://jsfiddle.net/6czap/3/

var $el = $(".example:first"), text = $.trim($el.text()),
    words = text.split(" "), html = "";

for (var i = 0; i < words.length; i++) {
    html += "<span>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";
};
$el.html(html).children().hide().each(function(i){
  $(this).delay(i*200).fadeIn(700);
});
$el.find("span").promise().done(function(){
    $el.text(function(i, text){
       return $.trim(text);
    });            
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...