EDIT: Ниже приведен код, с которым я столкнулся после многого.
Это базовая карусель, которая автоматически устанавливает стили для каждого слайда, дает каждому элементу класс, который вы можете использовать для управления контентом, имеет возможность приостанавливать при наведении, если необходимо, устанавливает фоновое изображение, используя атрибут данных для каждого div, и также работает с несколькими экземплярами на одной странице.
просто нужно вызвать его: $ ('# divName, # divName, # divName'). startTheCaro();
РЕШЕНИЕ:
(function($) {
$.fn.startTheCaro = function() {
return this.each(function() {
var $this = $(this);
var $thisChild = $this.children();
var theTransitionSpeed = 500; // Transition Speed
var theTransitionDelay = 3000; // Amount Of Time Slide Is Shown
var pauseOnHover = true; // Pause The Slide When Hovered // true or false
var thisImagePath = 'images/careers/'; // Background Image Path
var thisSlide = 0;
var thisSlideNum = 0;
var hoverPause = false;
var caroIsPlaying = false;
var newSlideName = 'thisCaroSlide';
var theSlidesTotal = $this.children().length-1;
// Setup each slide
$this.children().each(function() {
var $tC = $(this);
$tC.css('display', 'none');
var thisDataBgPath = $tC.data('bg');
// Set styles and classes
$(this).addClass('thisCaroSlide' + thisSlideNum);
$tC.css('position', 'absolute');
$tC.css('top', '0');
$tC.css('left', '0');
$tC.css('background', 'url(' + thisImagePath + thisDataBgPath + ') no-repeat top center');
$tC.css('background-position','center '+((topDist($(this))/$(window).height())*(-1*parAmount))+'px');
thisSlideNum++;
});
var playTheCaro = function() {
var getTheClass = ('.thisCaroSlide' + thisSlide);
if (hoverPause == true) {
// Pause on hover
} else {
if (thisSlide == theSlidesTotal) {
$this.find(getTheClass).fadeIn(theTransitionSpeed, function(){
$this.find('div:not(:first-child, :last-child)').css('display', 'none');
thisSlide++;
});
} else if (thisSlide == (theSlidesTotal+1)) {
$this.find('.thisCaroSlide' + theSlidesTotal).fadeOut(theTransitionSpeed, function(){
});
thisSlide = 1;
} else {
$this.find(getTheClass).fadeIn(theTransitionSpeed, function(){
});
thisSlide++;
};
};
};
playTheCaro();
// Pause the Carousel on Hover
var refreshIntervalId = setInterval(playTheCaro, theTransitionDelay);
$this.hover(function() {
if (pauseOnHover == true) {
refreshIntervalId = clearInterval(refreshIntervalId);
hoverPause = true;
}
}, function() {
if (pauseOnHover == true) {
refreshIntervalId = setInterval(playTheCaro, theTransitionDelay);
hoverPause = false;
}
});
});
};
}(jQuery));
Ну вот:
/* the recursion functions */
playTheCaro = function(selector, index, delay, interval) {
clearInterval(interval);
console.log(index , selector.length);
if(index >= selector.length ){
return;
}
interval = setInterval(function() {
/* the next element in is $(selector[index]) so you can do what you like with it.*/
$(selector[index]).fadeIn();
index++
playTheCaro(selector, index , delay,interval);
}, delay);
};
playTheCaro($('#some li'), 0, 2000);
Вам придется обмануть это, чтобы он соответствовал вашим потребностям.
вы можете увидеть пример: http://jsfiddle.net/J73Fu/2/
Закончилось использование Neta Meta, просто пришлось немного изменить его.
playTheCaro = function(selector, index, delay, interval) {
clearInterval(interval);
interval = setInterval(function() {
if(index >= selector.length ){
$('ul li:not(:first-child, :last-child)').css('display', 'none');
$('ul li:last-child').fadeOut(300, function(){
index = 0;
});
} else {
$(selector[index]).fadeIn(300);
index++
playTheCaro(selector, index , delay,interval);
}
}, delay);
};
$('#some li:first-child').css('display', 'block');
playTheCaro($('#some li'), 0, 2000);
Вот FIDDLE http://jsfiddle.net/J73Fu/4/
У вас есть еще один вопрос... Если вы пройдете через это, при перезапуске первый слайд удваивает задержку. Как вы можете установить задержку только для первой итерации?
Задайте function
в конце each
цикла. Используйте parameter
в своей функции start carousel
для прицеливания each
элемента, который должен исчезать.
...
playTheCaro($tC);
});
playTheCaro = function(thisSlide) {
setInterval(function() {
thisSlide.fadeIn();
}, 2000);
};
...
#caro
, поэтому сразу несколько экземпляров не #caro
:-P. Итак, у вас будет несколько слайд-шоу на одной странице?
.each
внутри.each
.theCurrentSlide.delay(i*2000).fadeIn()