jQuery FadeIn fadeOut与setInterval偶尔工作 [英] JQuery fadeIn fadeOut with setInterval working sporadically

查看:101
本文介绍了jQuery FadeIn fadeOut与setInterval偶尔工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆图像,需要使用精美的JQuery fadeIn和fadeOut每2秒一次旋转一次.我将HTML中的所有图像预加载,并使用setInterval计时器淡出当前图像,然后淡入下一幅图像.问题是有时在淡入/淡出过程中单击或滚动时, JS被打断,当前图像永不消失,下一幅图像逐渐消失,为您提供了两幅图像.

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.

我感觉到它与setInterval每2秒不能正确运行有关,但是有什么更好的方法来完成我需要的工作吗?

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?

这是一段代码:

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.

这篇关于jQuery FadeIn fadeOut与setInterval偶尔工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆