繁体   English   中英

jQuery setTimeout不起作用(图像幻灯片)

[英]Jquery setTimeout Isn't Working (Image Slideshow)

我正在为网站制作快速幻灯片。 我仍在使用Javascript / jQuery,因此将来可能会简化代码。 无论如何,我正在使用setTimeout函数来增加currentImage变量。 但是,它似乎无法正常工作,因为图像不会随着时间的流逝而改变。 后退和下一步按钮仍然有效,但似乎正在跳过其中一张图像。

$(document).ready(function(){
    var topofDiv = $("header").offset().top;
    var height = $("header").outerHeight();
    $(window).scroll(function(){    
        if($(window).scrollTop() > (topofDiv + height))
        {
            $("#nav").css("position","fixed");
        }
        else
        {
            $("#nav").css("position","static");
        }
    });
    var currentImage = 0;
    function autoPlay()
    {
        window.setTimeout(function(){
            currentImage++;
        }, 1000);
    };
    function slideImage()
    {
        if(currentImage == 0)
        {
            $(".img1").fadeIn(1000).show();
        }
        else
        {
            $(".img1").fadeOut(1000).hide();
        }
        if(currentImage == 1)
        {
            $(".img2").fadeIn(1000).show();
        }
        else
        {
            $(".img2").fadeOut(1000).hide();
        }
        if(currentImage == 2)
        {
            $(".img3").fadeIn(1000).show();
        }
        else
        {
            $(".img3").fadeOut(1000).hide();
        }
    };
    slideImage();
    autoPlay();
    $("#next").mouseenter(function(){
        $(this).css("color","black");
    });
    $("#next").mouseleave(function(){
        $(this).css("color","white");
    });
    $("#back").mouseenter(function(){
        $(this).css("color","black");
    });
    $("#back").mouseleave(function(){
        $(this).css("color","white");
    });
    $("#next").click(function(){
        clearTimeout(autoPlay);
        currentImage++;
        if(currentImage >= 3)
        {
            currentImage = 0;
        }
        slideImage();
    });
    $("#back").click(function(){
        clearTimeout(autoPlay);
        currentImage--;
        if(currentImage < 0)
        {
            currentImage = 2;
        }
        slideImage();
    });
});

请尝试以下code.You需要调用slideimage function里面setInteval ,你应该使用setInterval不是setTimeout 。所以在每1秒currentImage值将增加1,并显示相应的image.When currentImage值大于3,然后重置价值归零并通过调用slideimage dunction显示第一张图像

 var interval ="";
 interval = window.setInterval(function(){
        currentImage++;
        slideImage();
        if(currentImage > 3)
        {
          currentImage = 0;
          slideImage();
        }

    }, 1000);

    function RemoveInterval() {
       clearInterval(interval );
    }

next and back button click调用RemoveInterval

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM