我有以下代码,通过具有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]')
的任何一个访问定时器以便能够暂停它。我怎么能够?
你可以添加你的HTML,它可能会更容易添加一个片段与运行的例子与你想要的修复 –