我有以下代码遍历页面上具有data-slides
属性的每个div,该属性指定要显示的一些图像。它通过淡入淡出它们来动画循环中的不同图像:
(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 Thunder的建议,我用一个可以暂停的单独计时器更新了它:
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 :(得分: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的信用。