jQuery图片库非功能性淡入淡出效果

问题描述:

这是一个简单的图库脚本,用于淡入和淡出带有背景图像的div.它很慢,无法正常工作.

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?

next()只是找到选择器的下一个同级对象.它不会跟踪您的位置.我会做一个setInterval,并与它一起传递当前索引.例如:

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() });

为避免元素移位,请将函数作为回调添加到fadeOut,而不要让它们异步发生.

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

注意:一般而言,全局变量并不是最好的方法,而只是给您一个想法.更好的形式是有一个函数,该函数用setTimeout进行调用,并每次都传递递增的ind参数.

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.

未测试.