使用setInterval通过JQuery暂停幻灯片放映吗?

问题描述 投票:1回答:1

首先,我想说我是JS / JQuery的新手。

我正在尝试使用暂停和播放按钮制作背景图像幻灯片。

我想出了如何使用clearInterval暂停它,但是我一生都无法弄清楚如何使其从暂停点重新开始。我知道有几个与此相关的主题,但是我无法让它们与幻灯片一起使用。

以下代码:

$(document).ready(function(){
var count = 0;
var images = ["img1.jpg","img2.jpg","img3.jpg","img4.jpg"];
var image = $(".fader");
var timer = false;


image.css("background-image","url("+images[3]+")");

var timer = setInterval(function(){
    image.fadeOut(500, function(){
        image.css("background-image","url("+images[count++]+")");
        image.fadeIn(500);
    });
    if(count==images.length){
        count = 0;
    }
},1000);

$("#pauseButton").click(function(){
    clearInterval(timer);
 });

 $("#startButton").click(function(){
     setInterval(timer);
});

});

谢谢你。

jquery setinterval slideshow clearinterval
1个回答
1
投票

基本上,您可以使“下一张幻灯片”功能可重复使用,然后在需要启动幻灯片放映时使用它,无论是初次启动还是以后重新启动。

但是将各种逻辑位放在离散的,命名良好的函数中可以帮助代码更容易地流动,并且更易于阅读/维护,这是一些建议(用***标记:]

$(document).ready(function() {
    var count = 0;
    var images = ["img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg"];
    var image = $(".fader");
    var timer = 0; // *** Timer handles are numbers. `false` works, but...

    // *** Reusable function to target with `setInterval`
    function nextSlide() {
        image.fadeOut(500, function() {
            image.css("background-image", "url(" + images[count] + ")"); // *** Removed increment here, see below
            image.fadeIn(500);
        });
        count = (count + 1) % images.length; // *** Easy way to do roll-around
    }

    // *** Reusable "start" function
    function startSlideShow() {
        if (!timer) { // *** Don't try to start it if already running
            timer = setInterval(nextSlide, 1000);
        }
    }

    // *** Reusable "stop" function
    function stopSlideShow() {
        clearInterval(timer); // *** Safe to call with `0`, so no need to branch
        timer = 0;
    }

    // *** Stop when pause button clicked
    $("#pauseButton").click(stopSlideShow);

    // *** (Re)Start when pause button clicked
    $("#startButton").click(startSlideShow);

    // *** Start the slideshow automatically
    image.css("background-image", "url(" + images[3] + ")");
    startSlideShow();
});
© www.soinside.com 2019 - 2024. All rights reserved.