JQuery fadeIn fadeOut with setInterval working sporadically
I have a bunch of images that need to rotate in and out one at a time every 2 seconds with fancy JQuery fadeIn and fadeOut. I have all the images in the HTML to pre-load them and a setInterval timer that fades the current image out, then fades the next image in. Problem is that sometimes when you are clicking or scrolling during the fade in/out process, the JS gets interrupted and the current image never disappears and the next one fades in giving you two images.
I get the feeling it has something to do with setInterval not running properly every 2 seconds, but are there any better ways to accomplish what I need?
Here's a snippet of code:
HTML
<a href="javascript:;">
<img id="img1" src="image1.gif" />
<img id="img2" src="image2.gif" style="display:none;" />
<img id="img3" src="image3.gif" style="display:none;" />
</a>
JS
var numImages = 3;
var currentImage = 1;
imageInterval = window.setInterval("changeImage();", 2000);
function changeImage()
{
$("#img" + currentImage).fadeOut("slow", function() {
if (currentImage >= numImages)
{
currentImage = 0;
}
$("#img" + (currentImage + 1) ).fadeIn("slow", function() {
currentImage++;
});
});
}
Have you thought about using the Cycle Plugin? It sounds like this does exactly what you're trying to do, and it offers a lot of flexibility. I've used this plugin myself with great results. Highly recommended.
Just off the top of my head ... why are you doing the currentImage bookkeeping in the callback functions? It seems to me this is easier, and might even have something to do with your problem:
function changeImage()
{
$("#img" + currentImage).fadeOut("slow");
currentImage = (currentImage >= numImages) ? 1 : currentImage + 1;
$("#img" + currentImage).fadeIn("slow");
}
You have id="img2" twice.
Can you not simpify - calculate the current and next id first. Then do your $().fadeOut() and on the next line $().fadeIn() and avoid all of the function complexity.
链接地址: http://www.djcxy.com/p/64756.html