setinterval() 和 clearinterval() - 清除时,不会自动设置动画 [英] setinterval() and clearinterval() - when cleared, does not animate automatically

查看:27
本文介绍了setinterval() 和 clearinterval() - 清除时,不会自动设置动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试构建一个动画背景图像,它将在一组图像中循环.

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.

脚本如下:

$(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.

推荐答案

这应该为你做.

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();
});

这篇关于setinterval() 和 clearinterval() - 清除时,不会自动设置动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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