JQuery image gallery non functional fade effects

我们两清 提交于 2019-12-02 21:56:27

问题


Here is a simple image gallery script for fading in and out divs with background images. It is slow and not working properly.

  • It would appear all images are appearing and disappearing together without any animation
  • This gallery should fade each image out into the next one

    function gallery() {
                timerp = window.setInterval(function() {
                    $('.cornerimg').fadeOut(2000);
    
                    if ($('.cornerimg:visible') == $('.cornerimg').last()) {
                        $('.cornerimg').first().fadeIn(2000);
                    } else {
                        $('.cornerimg').next().fadeIn(2000);
                    };
                }, 6000);
            }
    }
    

Any ideas what has gone wrong with it?


回答1:


next() just finds the next sibling for the selector. It doesn't keep track of where you are. I would do a setInterval and pass the current index along with it. For example:

function gallery() {
        ind = 0;
        l = $('.cornerimg').length;
        $('.cornerimg').fadeOut(500);        

        window.setInterval( function() {
            if ( ind > 0 ) $('.cornerimg').eq(ind-1).fadeOut(2000);
            if (ind == l) {
                ind = 0;
            }
            $('.cornerimg').eq(ind).fadeIn(500);
            ind++;
        }, 2000 );
}

$(function() { gallery() });

To avoid shifting of elements, add the function as a callback to the fadeOut instead of having them happen asynchronously.

NOTE: Global variables are not the best way to go in general, but just to give you an idea. The better form is to have a function that calls itself with setTimeout and passes the incremented ind argument each time.

UNTESTED.



来源:https://stackoverflow.com/questions/6536077/jquery-image-gallery-non-functional-fade-effects

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