开发者

jQuery Array fadeIn not working

开发者 https://www.devze.com 2023-02-14 22:07 出处:网络
I\'m trying to fadeIn an fadeOut items in the array to a div. I\'m trying to make this work in a fadeIn fadeOut manner. So first item fades in开发者_开发知识库 stays for 3 secodns then fades back out,

I'm trying to fadeIn an fadeOut items in the array to a div. I'm trying to make this work in a fadeIn fadeOut manner. So first item fades in开发者_开发知识库 stays for 3 secodns then fades back out, then the next item fadein, 3seocnds then fade out and so on..... why is wrong with my code. Check http://jsfiddle.net/Fpu2E/1/


The code you're using won't work for various reasons - having zero delay between calling fadeOut and fadeIn means you won't get the 3 second delay you're looking for between fading in and out, and that calling both functions lead to some strange effects with the jQuery effects queue.

A better option would be to use a recursive function together with delay to do this:

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

function changeNews() {
    div.fadeIn(3000).delay(3000).fadeOut(3000, function() {
        changeNews();
    }).text(news[count++]);
}

changeNews();

A simple demo of this can be found here: http://jsfiddle.net/Fpu2E/4/


This works...

var news = ['news1', 'news2', 'news3'],
    count = news.length,
    currentItem = 0;

showNextItem = function() {

    $('div').text(news[currentItem++]).fadeIn(3000, function() {
        var element = $(this);
        setTimeout(function() {
            element.fadeOut(1000, function() {
                if (currentItem < count) {
                    showNextItem();
                }
            });

        }, 3000);
    });

};

showNextItem();

jsFiddle.

0

精彩评论

暂无评论...
验证码 换一张
取 消