jQuery setinterval() 和 clearinterval() - 清除时,不会自动动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10442452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:21:13  来源:igfitidea点击:

setinterval() and clearinterval() - when cleared, does not animate automatically

jquerybackgroundslideshowsetintervalclearinterval

提问by Kasper Lewau

So I'm trying to build an animating background image which will cycle through an array of images.

因此,我正在尝试构建一个动画背景图像,它将在一系列图像中循环。

The idea is also that when you click any navigation element on the page, the cycle will pause.

这个想法也是当您单击页面上的任何导航元素时,循环将暂停。

When you click on the home button, the cycle is to start up again (from the current image).

当您单击主页按钮时,循环是再次启动(从当前图像)。

This works in it's current state, however the cycle is not automatic upon re-firing it, instead you have to press the home button for each fade/slide/whatever.

这在当前状态下有效,但是在重新启动它时循环不是自动的,而是您必须为每个淡入淡出/滑动/任何东西按下主页按钮。

The script is as follows:

脚本如下:

$(document).ready(function(){

    var imgArr = new Array(
        'img/slides/slide1.jpg',
        'img/slides/slide2.jpg',
        'img/slides/slide3.jpg');

    var preloadArr = new Array();
    var i;


    // Preload
    for(i=0; i < imgArr.length; i++){
        preloadArr[i] = new Image();
        preloadArr[i].src = imgArr[i];
    }

    var currImg = 1;
    var IntID = setInterval(startSlider, 4000);

    // Image Rotator

    function startSlider(){
        $('.mainbg').animate({opacity: 0}, 1200, "easeInOutExpo", function(){
            $(this).css('background','url(' + preloadArr[currImg++%preloadArr.length].src + ') no-repeat center center fixed');
            $(this).css({'background-size': 'cover' , '-webkit-background-size': 'cover' , '-moz-background-size': 'cover' , '-o-background-size': 'cover' ,});
            }).animate({opacity: 1}, 1200, "easeInOutExpo");
        }

    function stopSlider() {
        clearInterval(IntID);
    }

    $(".topnav ul li a").click(stopSlider);

    $("#home").click(startSlider);
});

If someone could please point me in the correct direction with this, it'd be greatly appreciated! Best regards, Kasper.

如果有人能指出我正确的方向,我将不胜感激!最好的问候,卡斯帕。

回答by Matthew Nie

This should do it for you.

这应该为你做。

var IntID = setTimer();

function setTimer(){
     i = setInterval(startSlider, 4000);
     return i;
}

function stopSlider() {
    clearInterval(IntID);
}

//Restart Timer
// Option 1 make a restartSlider function and call it
$("#home").click(restartSlider);
function restartSlider(){
      IntID = setTimer();
}

//Option 2 create an anonymous function only for that click event.
$("#home").click(function(){
     IntID = setTimer();
});