问题
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