Я создал плагин jQuery, который работает как слайд-шоу. Вся моя проблема в том, что она сначала исчезает, а затем исчезают следующие изображения. Что немного странно. Я думал весь день и действительно избиваю его. Может ли кто-нибудь мне помочь? Вот информация:
Ниже приведен список веб-сайтов с текущим слайд-шоу:
www.ms-models.com
www.royal-fci.com
Теперь ПРОБЛЕМА:
есть, естественно, куча изображений для слайд-шоу, чтобы вывести их из себя. Теперь слайд-шоу заставляет первое изображение исчезнуть, а затем запустило следующее изображение. Я хочу, чтобы слайд-шоу начинало исчезать в следующем изображении, когда текущее изображение уже начало исчезать. Точно так же, как сотни слайд-шоу на многих веб-сайтах. Нет необходимости давать ссылку.
Вот сценарий плагина:
(function(){
/* function read_line (path_to_file, container, tag, url_prefix)
{
myObject = {}; //myObject[numberline] = "textEachLine";
$.get(, functipath_to_fileon(myContentFile) {
var lines = myContentFile.split("\r\n");
for(var i in lines)
{
myObject[i] = i;
container.append('<'+tag+'>'+"<img src='"+url_prefix+'/'+lines[i]+"'>"+'</img>'+'</'+tag+'>');
}
}, 'text');// end of anonymous function
} */
$.fn.mtSlideGallery = function(options){
var options = $.extend({
fullWidth : false, // this makes a full background slideshow
FadeIn : 2, // this is the duration of fading in
FadeOut : 2, // this is the duration of fading out
visibilityDuration : 2, // this is the duration of visible image
startSlide : 1, // this is the first slide when the page loads
height : '100%',
height_fixed : true,
enable_error : false,
enable_gallery : false,
slide_previous : '.slide-left-control', // this is the name of class for previous-picture-handle
slide_next : '.slide-right-control', // this is the name of class for next-picture-handle
print_output : false,
print_area : '.slideshow-label',
seo_campatible : false, // this allows the script to print the title of each slide out into a h1-h6 tag
seo_suggestion : 'h2' // this allows the user to specify which h1-h6 tag be used. default is h6
/*auto_generate_from_file : false, // if true, then it will generate the div tag based on a file given
auto_generate_url : false, // if true, then a url_prefix is added to each line of text
auto_generate_tag : 'div', // the tag inside which the image tags nest. default is div and it is recommended no to change
auto_generate_url_prefix : "" // this is the url added to each image address. Depends on auto_generate_url options*/
}, options)
// develope $fn protype
return this.each(function(){
if(options.print_output === true)
{
var text_for_output = $(this).children('div').eq(options.startSlide).children('img').attr('alt');
$(options.print_area).text(text_for_output);
}
if(options.fullWidth === true)
{
$("body").css({'padding' : '0', 'margin' : '0'});
$("body").css({'overflow' : 'hidden'});
$("html").css({'padding' : '0', 'margin' : '0'});
$(this).css({'width' : '100%', 'height' : options.height});
$(this).css({'margin' : '0', 'padding' : '0'});
}
if(options.height_fixed === true)
{
$(this).css({'overflow' : 'hidden'});
}
var slideWrapper = $(this);
var slidesGroup = slideWrapper.children('div');
slidesLength = slidesGroup.length;
if(options.enable_error == true)
{
if(options.startSlide > slidesLength)
{
alert("Please correct the \"slideStart\" option. The number has to be less than the total number of images.")
}
}
i = options.startSlide;
slidesGroup.not(":eq("+i+")").hide();
console.log(slidesLength);
////////////////////// Print To label if true
var print_label = function(i)
{
var label = slidesGroup.eq(i).children('img').attr('alt');
$(options.print_area).text(label);
}
;
///////////////////// End of printing label
//////////////// GALLERY SLIDESHOW IF ENABLED USES THIS SCRIPT
if(options.enable_gallery === true)
{
$(options.slide_previous).click(function(event){ // this is a click event for the previous picture in the queue
event.preventDefault();
event.stopPropagation();
slidesGroup.eq(i).hide();
if(i === slidesLength)
{
i=0;
}
i -= 1;
slidesGroup.eq(i).show();
if(options.print_output === true)
{
print_label(i);
}
});
$(options.slide_next).click(function(event){ // this is a click event for the next picture in the queue
event.preventDefault();
event.stopPropagation();
slidesGroup.eq(i).hide();
if(i === slidesLength)
{
i=0;
}
i += 1;
slidesGroup.eq(i).show();
if(options.print_output === true)
{
print_label(i);
}
});
}
////////////////////// END OF GALLERY-ENABLED SCRIPT
////////////////////////////////////////////////////////
var slideShow = function () {
slidesGroup.eq(i).fadeOut(options.FadeOut*1000, function(){
slidesGroup.eq(i).hide();
i += 1;
if(i === slidesLength)
{
i=0;
}
slidesGroup.eq(i).fadeIn(options.FadeIn*1000);
if(options.print_output === true)
{
print_label(i);
}
})
}
setInterval(slideShow, options.visibilityDuration*1000);
})
}
})(jQuery)
Теперь слайд-шоу заставляет первое изображение исчезнуть, а затем запустило следующее изображение. Я хочу, чтобы слайд-шоу начинало исчезать в следующем изображении, когда текущее изображение уже начало исчезать.
Проблема здесь в том, что вызов исчезать на следующем слайде является частью анонимной функции обратного вызова, которая не срабатывает до завершения первоначальной анимации jQuery. Вы захотите переписать свой код так, чтобы функции $.fadeOut()
и $.fadeIn()
выполнялись одновременно:
var transition = function() {
//Determine the index of the next slide to show, based on the current index
var next_index = (current_index < slidesLength - 1) ? current_index + 1 : 0;
//Fade out the 'old' slide while fading in the 'new' slide
slidesGroup.eq(current_index).fadeOut({
duration: options.FadeOut*1000,
start: function() {
slidesGroup.eq(next_index).fadeIn({
duration: options.FadeIn*1000
});
},
complete: function() {
//Update the value of current_index
current_index = next_index;
}
});
}
Однако эта функция в значительной степени ограничивает вас переходом только вперед. Вы можете включить аргумент функции, который указывает направление перехода (вперед и назад), которое будет определять индекс следующего слайда.
Работа jsFiddle: http://jsfiddle.net/gh25s/
EDIT: Чтобы уточнить, вы захотите заменить эту часть своего кода:
var slideShow = function () {
slidesGroup.eq(i).fadeOut(options.FadeOut*1000, function(){
slidesGroup.eq(i).hide();
i += 1;
if(i === slidesLength) {
i=0;
}
slidesGroup.eq(i).fadeIn(options.FadeIn*1000);
if(options.print_output === true) {
print_label(i);
}
});
};
с этим:
var slideShow = function() {
//Determine the index of the next slide to show, based on the current index
var next_index = (i < slidesLength - 1) ? i + 1 : 0;
//Fade out the 'old' slide while fading in the 'new' slide
slidesGroup.eq(i).fadeOut({
duration: options.FadeOut*1000,
start: function() {
slidesGroup.eq(next_index).fadeIn({
duration: options.FadeIn*1000
});
},
complete: function() {
//Update the value of i
i = next_index;
}
});
}
Кроме того, использование имени переменной i
во всем вашем коде запутывает. Я бы предложил дать более содержательное описательное имя, например current_index
. Имена переменных, подобные i
, обычно считаются временными локальными переменными, которые используются для какой-либо итерации.