0

I have been trying to make a simple word sequence display program in jQuery. I want to achieve a simple program that can take sentence as input and its output can be displayed in sequence of words.

Now how can I make this program show these words in sequence like below

 <div class="bar">One Two </div>  //(hide it after few seconds and show next line)
 <div class="bar">Three Four </div> //(hide it after few seconds and show next line)
 <div class="bar">Five Six </div> //(hide it after few seconds and show next line)
 <div class="bar">Seven </div> //(hide it after few seconds)

The number of words displayed at a time in sequence can be configured using wordCount var in my program

My Program at JSFiddle

I have tried a lot of options on this and its always displaying the last word "Seven" in the div. The animation seems to work right amount of time, that makes me think it has to do with the way JS handles delay in animations.

I guess this goes back to the clear understanding of few things Not sure how JavaScript is handing the delay here.

I have tried following but did not work - setTimeout - calling the function with a delay - jQuery.delay() call

When I put the console.log messages it does show me all the words in sequence however the div always contains the last word.

I guess JavaScript is not waiting for the animations to complete and the last word reaches too soon and animation continues later.

I guess the main line of code to look at would be

    $('.bar').fadeIn(1000).text(displayWords).fadeOut(1000);

Any help and insight on this would be greatly appreciated.

4

2 回答 2

1

Try below version using setInterval,

var words = $('.foo').text().split(' ');
var index = 0;
var wordCount = 3;

var showHide = setInterval(function () {
    var displayWords = "";

    var mx = index + wordCount;
    if (mx > words.length) mx = words.length;
    for (var i = index; i < mx; i++) {
        displayWords += words[i] + " ";
    }

    $('.bar').fadeIn(1000).text(displayWords).fadeOut(1000);
    index = mx;
    if (index > words.length) clearInterval(showHide);    
}, 2000);

DEMO: http://jsfiddle.net/9T4HE/15/

于 2013-03-18T19:28:16.300 回答
0

Have a look at jQuery.queue()...

http://api.jquery.com/queue/

here is the code from the above url:

var div = $("div");
function runIt() {
    div.show("slow");
    div.animate({left:'+=200'},2000);
    div.slideToggle(1000);
    div.slideToggle("fast");
    div.animate({left:'-=200'},1500);
    div.hide("slow");
    div.show(1200);
    div.slideUp("normal", runIt);
}
function showIt() {
    var n = div.queue("fx");
    $("span").text( n.length );
    setTimeout(showIt, 100);
}
runIt();
showIt();

The runIt() method adds the animations to the queue and the showIt method invokes the queue with a timeout.

The URL above also shows a demo of various animations running in succession.

HTH

于 2013-03-18T19:29:15.647 回答