2017-12-02 88 views
0

我有以下代码,通过具有data-slides属性的页面上的每个div指定要显示的图像。它通过淡入和淡出他们的动画在一个循环中不同的图像:OnClick的暂停动画

(function($) { 
'use strict'; 
$('[data-slides]').each(function(){ 
     var $slides = $(this); 
     var images = $slides.data('slides'); 
     var count = images.length; 
     var number = 0; 
     var slideshow = function() { 
      $slides 
       .css('background-image', 'url("' + images[number%count] + '")') 
       .show(0, function() { 
        setTimeout(slideshow, 3500); 
       }); 
       number++; 
     }; 

     slideshow(); 
    }); 
}(jQuery)); 

我想要做的是有再次启动的幻灯片动画按钮暂停正在制作动画的特定元素,然后另一个按钮。我怎样才能做到这一点?谢谢!

编辑

使用从Flash雷霆的建议,我已经有独立的定时器,可暂停更新它:

function Timer(callback, delay) { 
    var timerId, start, remaining = delay; 

    this.pause = function() { 
     window.clearTimeout(timerId); 
     remaining -= new Date() - start; 
    }; 

    this.resume = function() { 
     start = new Date(); 
     window.clearTimeout(timerId); 
     timerId = window.setTimeout(callback, remaining); 
    }; 

    this.resume(); 
} 

function runSlideshow(div){ 
    var $slides = div; 
    var images = $slides.data('slides'); 
    var count = images.length; 
    var number = 0; 
    this.slideshow = function() { 
     $slides 
      .css('background-image', 'url("' + images[number%count] + '")') 
      .show(0, function() { 
       timer.resume(); 
      }); 
      number++; 
    }; 
    var timer = new Timer(this.slideshow, 3500); 

    this.slideshow(); 
} 

(function($) { 
    'use strict'; 
    $('[data-slides]').each(function() { 
      var run = new runSlideshow($(this)); 
      run.slideshow(); 
    }); 
}(jQuery)); 

这工作,但我需要能够从$('[data-slides]')的任何一个访问定时器以便能够暂停它。我怎么能够?

+0

你可以添加你的HTML,它可能会更容易添加一个片段与运行的例子与你想要的修复 –

回答

0
function Timer(callback, delay) { 
    var timerId, start, remaining = delay; 

    this.pause = function() { 
     window.clearTimeout(timerId); 
     remaining -= new Date() - start; 
    }; 

    this.resume = function() { 
     start = new Date(); 
     window.clearTimeout(timerId); 
     timerId = window.setTimeout(callback, remaining); 
    }; 

    this.resume(); 
} 

var timer = new Timer(function() { 
    alert("Done!"); 
}, 1000); 

timer.pause(); 
// Do some stuff... 
timer.resume(); 

致谢Tim Down

+0

你认为你可以定制这个我的代码?我不是本地的JS开发人员,所以我不太清楚这是如何涉及的。 – Tometoyou

+0

将此函数添加到您的代码中,使用具有相同参数而不是'setTimeout'的'timer',然后您可以随时调用'timer.pause()'和'timer.resume()'。例如在'onclick'事件中。 –

+0

好酷我已经设法做到这一点。但是,如何从单独的onclick事件访问计时器?因为我对元素运行了一个foreach循环,所以很难访问它。我已更新我的代码... – Tometoyou