jQuery Array fadeIn not working

南笙酒味 提交于 2019-12-11 16:02:57

问题


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/


回答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/




回答2:


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.



来源:https://stackoverflow.com/questions/5209954/jquery-array-fadein-not-working

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