最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Best way to fade and loop through a set of divs - Stack Overflow

programmeradmin2浏览0评论

Let's say I have the following divs:

<div class="a">You are funny.</div>
<div class="b">You are smart.</div>
<div class="c">You are cool.</div>

What is the best way to show div.a for 5 seconds, then fade out and fade in div.b for 5 seconds and then to div.c and then back to div.a and continue looping for an infinite amount of time?

Thanks :)

Let's say I have the following divs:

<div class="a">You are funny.</div>
<div class="b">You are smart.</div>
<div class="c">You are cool.</div>

What is the best way to show div.a for 5 seconds, then fade out and fade in div.b for 5 seconds and then to div.c and then back to div.a and continue looping for an infinite amount of time?

Thanks :)

Share Improve this question edited Apr 24, 2011 at 4:57 stewart715 asked Apr 24, 2011 at 4:44 stewart715stewart715 5,63711 gold badges49 silver badges81 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You can use an array of values and loop thru them.

var div = $('div').hide(),
    news = ['news1', 'news2', 'news3'],
    count = 0;

function changeNews() {
    div.fadeIn().delay(500).fadeOut(function() {
        changeNews();
    }).text(news[count++])
    if (count == news.length) {
        count = 0;
    }
}
changeNews();

Check working example at http://jsfiddle/qJa3h/

How about a jQuery plugin? I haven't tested it but something like this should get you started:

(function($) {

    $.fn.keepFadingToNext = function(options) {
        var defaults = {
            duration: 5000
        };

        var settings = $.extend({}, defaults, options);

        var original = this;

        var doAnimations = function(element) {
            element.fadeIn(settings.duration, function() {
                element.fadeOut(settings.duration, function() {
                    var next = element.next();

                    if (next.length === 0) {
                        next = original;
                    }

                    doAnimations(next);
                });
            });
        };

        doAnimations(original);

        return original;
    };

})(jQuery)

$('.a').keepFadingToNext();

// or
$('.a').keepFadingToNext({ duration: 3000 });
发布评论

评论列表(0)

  1. 暂无评论