понедельник, 17 октября 2011 г.

Продолжаем писать слайдер

Обещанный рассказ про скрипт для слайд-шоу.

Сначала определим классы для самого слайдера и для каждого изображения внутри.

function SimpleSlider(width, height, duration){
 this.type = "SimpleSlider";
 this.width = width;
 this.height = height;
 this.duration = (duration) ? duration : 1000;
 this.images = new Array(); //картиночки
 
 this.imgprefix = 'slider-img-';
 this.currimage = 0;
}
function SimpleSliderItem(url, width, height, itemid){
 this.type = "SimpleSliderItem";
 this.url = url;
 this.width = width;
 this.height = height;
 this.itemid = itemid;
}

Добавляем изображение (slider.addImage("..."), разумеется). Перед добавлением кэшируем его, создавая объект типа Image. Этот объект хорош разве что тем, что то, что попадает в его src, будет обязательно прокешировано. Как вставить его на страницу - загадка. Поэтому заполняем images нашим собственным типом и не забываем, что добавлять больше 9999 картинок - нельзя :):

SimpleSlider.prototype.addImage = function(url) {
    if(this.images.length >= 9999)
       return;
    //Caching
    var Image1= new Image(this.width,this.height);
    Image1.src = url;
   //Appending
    this.images.push(new SimpleSliderItem(url, this.width, this.height, this.images.length));
};

SimpleSlider.prototype.insertImage = function(id) {
    if (this.images.length > id){
  var imgElem = document.createElement('img'); 
  imgElem.setAttribute('id', this.imgprefix + id);
  imgElem.setAttribute('class', 'slider-block');
  
  imgElem.setAttribute('src', this.images[id].url);
   
  imgElem.setAttribute('style', 'width: ' + this.images[id].width + '; height: ' + this.images[id].height + '; z-index: ' + (this.images.length - id) + ';');
  return imgElem;
 } else {
  return null;
 }  
};

Вставить все, одно под одним:

SimpleSlider.prototype.insertImages = function(imgElem) {
 imgElem.setAttribute('style', 'width: '+this.width+'; height: ' + this.height + ';');
    for(var img in this.images)  
 {
  var elem = this.insertImage(img);
  if(elem)
   imgElem.appendChild(elem);
 }
};

И вот настало время сделать сам слайдер. Какое изображение следующее - он узнают из функции nextImageId(), а текущее - currImageId(). Если бы это был C#, мы бы оформили их как параметры класса.

В changeImage применяем jQuery. Сначала находим то, что надо и то, на что его менять - а потом меняем. Правда, возникает проблема: в 1-ой картинке z_index больше, чем в последней, и если сделать ей show, то она просто прыгнет наверх безо всякого fade. Поэтому мы ставим последней по счёту картинке z-Index в 9999 (поэтому добавлять можно не больше 9998 изображений), в currImage.fadeOut встроили небольшую callback функцию, которая возвращает z-Index обратно:

SimpleSlider.prototype.nextImageId = function() {
 if(!this.images.length)
  return null;
 this.currimage++;
 if(this.currimage >= this.images.length)
  this.currimage = 0;
 return "#" + this.imgprefix + this.currimage;
};

SimpleSlider.prototype.currImageId = function() {
 if(!this.images.length)
  return null;
 return "#" + this.imgprefix + this.currimage;
};

SimpleSlider.prototype.changeImage = function() {
 var currImage = $(slider.currImageId());
 var nextImage = $(slider.nextImageId());
 isLastItem = !this.currimage;
 if(isLastItem)
  currImage.css('z-Index', '9999');
 currImage.fadeOut(this.duration, function() {
   if(parseInt(currImage.css('z-Index')) == 9999)
    currImage.css('z-Index', '1');
  });
 nextImage.show();
};

Комментариев нет:

Отправить комментарий