2012-06-02 1 views
3

Я искал карусель изображений, которая будет отображать сразу несколько изображений, реагирует и петляет бесконечно.Как изменить Elastislide, так что он бесконечно петляет

Elastislide представляется наиболее подходящим (http://tympanus.net/Development/Elastislide/index2.html).

Единственный другой практический вариант, который я смог найти, - это Liquid Carousel от John Nikolakis, который кажется более старым и менее элегантным.

У меня есть Elastislide для автовоспроизведения (сорта), используя аналогичный метод Метод clearTimeout(), показанный на http://www.w3schools.com/js/js_timing.asp, но как только он достигает конца, он останавливается, поскольку время просто вызывает следующую кнопку (.es-нав-другому).

Я надеюсь, что кто-то может помочь мне с изменением Elastislide, чтобы сделать его бесконечным, или я открыт для предложений по другому решению, которое соответствует моим 3 требованиям (перечисленным выше).

На данный момент я работаю над локальной установкой OpenCart, но могу установить статический образец и предоставить ссылку, если это поможет.

Любая помощь или совет был бы весьма признателен, потратили много времени на это до сих пор, как я полный дилетант в JavaScript :)

ответ

1

Я сделал это взлом toggleControls() функцию, вместо того, чтобы скрываться навигацию, чтобы добавить первый элемент/добавить последний элемент. Автоматическая коррекция суммы, когда вы находились в начале/конце предметов, фактически помогла сделать трюк. К сожалению, это прерывает анимацию, если используется ослабление.

// modified version of _toggleControls 
    _toggleControls  : function(dir, status) { 

     // show/hide navigation buttons 
     if(dir && status) { 
      if(status === 1) 
       (dir === 'right') ? this.$navNext.show() : this.$navPrev.show(); 
      else 
       if (dir === 'right') { 

        this.$slider.append(this.$slider.children('li:first').clone()) ; 
        this.$slider.children('li:first').remove(); 
       } else { 

        this.$slider.prepend(this.$slider.children('li:last').clone()) ; 
        this.$slider.children('li:last').remove(); 
       } 
     } 
     else if(this.current >= this.itemsCount - 1 || this.fitCount >= this.itemsCount) 
       this.$navNext.hide(); 

    }, 
+0

очень хороший ответ вы получили мой голос, но есть еще одна вещь, как предотвратить карусель слайд обратно в первых пунктов после нескольких секунд нажатия нав управления ? – motto

2

Этот код создает бесконечный цикл, сохраняет анимации и показывает кнопки навигации с обеих сторон, если на странице больше элементов, чем показано на странице. Функция _toggleControls остается той же, что и в оригинальной версии.

// modified version of _slide 
_slide    : function(dir, val, anim, callback) { 

     // if animating return 
     if(this.$slider.is(':animated')) 
      return false; 

     // current margin left 
     var ml  = parseFloat(this.$slider.css('margin-left')); 

     // val is just passed when we want an exact value for the margin left (used in the _slideToCurrent function) 
     if(val === undefined) { 

      // how much to slide? 
      var amount = this.fitCount * this.itemW, val; 

      if(amount < 0) return false; 

      // make sure not to leave a space between the last item/first item and the end/beggining of the slider available width 
      if(dir === 'right' && this.sliderW - (Math.abs(ml) + amount) < this.visibleWidth) { 
       for (var i=0;i<this.fitCount;i++) { // add elements 
        this.$slider.css('margin-left', '+=' + this.itemW); 
        this.$slider.append(this.$slider.children('li:first').clone()) ; 
        this.$slider.children('li:first').remove(); 
       } 
      } else if (dir === 'left' && Math.abs(ml) - amount < 0) { 
       for (var i=0;i<this.fitCount;i++) { // add elements 
        this.$slider.css('margin-left', '-=' + this.itemW); 
        this.$slider.prepend(this.$slider.children('li:last').clone()) ; 
        this.$slider.children('li:last').remove(); 
       } 
      } 

      (dir === 'right') ? val = '-=' + amount : val = '+=' + amount 

     } 
     else { 
      var fml  = Math.abs(val); // future margin left 

      if(Math.max(this.sliderW, this.visibleWidth) - fml < this.visibleWidth) { 
       val = - (Math.max(this.sliderW, this.visibleWidth) - this.visibleWidth); 
       if(val !== 0) 
        val += this.options.margin; // decrease the margin left if not on the first position 

       // show/hide navigation buttons 
       this._toggleControls('right', -1); 
       fml = Math.abs(val); 
      } 

      // show/hide navigation buttons 
      if(this.fitCount < this.itemsCount) 
       this._toggleControls('left', 1); 
      else 
       this._toggleControls('left', -1); 

      if(Math.max(this.sliderW, this.visibleWidth) - this.visibleWidth > fml + this.options.margin) 
       this._toggleControls('right', 1); 
      else 
       this._toggleControls('right', -1); 

     } 

     $.fn.applyStyle = (anim === undefined) ? $.fn.animate : $.fn.css; 

     var sliderCSS = { marginLeft : val }; 

     var instance = this; 

     this.$slider.applyStyle(sliderCSS, $.extend(true, [], { duration : this.options.speed, easing : this.options.easing, complete : function() { 
      if(callback) callback.call(); 
     } })); 

    }, 
1

У меня была такая же проблема, как и у ОП, но я не мог заставить любое из вышеперечисленных решений работать. Не уверен, что я делал что-то неправильно или если код Elastislide изменился с тех пор, как были написаны эти решения.

Я нашел этот плагин, который, кажется, удовлетворяет всем тем же критериям, что и у OP: отзывчивая карусель с автоиграми и бесконечным циклом.

http://caroufredsel.dev7studios.com/

Надеюсь, это поможет кому-то еще, что находит эту статью таким же образом я сделал.

+0

Ницца! Thx alot :) – william

1

Добавьте этот код в функцию _initEvents после - var instance = this; чтобы сделать автовоспроизведение elastislide.

window.setInterval(function(){ 
       instance._slide('right'); 
      }, 7000); 
+0

Это будет автоматически воспроизводиться, но не учитывает, что происходит, когда ползунок достигает последнего слайда или когда пользователь нажимает следующую кнопку вручную. Это остановится на последнем слайде. Если пользователь нажимает рядом вручную с отметкой 6500 мс, слайдер будет перемещаться вперед дважды подряд. – ORyan

9

Эластилидный код развился, и вышеуказанное решение не работает. Поэтому я разработал свое собственное решение.

Этот код обеспечивает автовоспроизведение elastislide, и при достижении последнего слайда он возвращается к первому слайду, чтобы быть более эргономичным, чем карусель с бесконечным циклом.

Этот код должен быть добавлен в функции _initEvents после вар self = this;

var translation = 0; 
// width/height of an item (<li>) 
var itemSpace = this.options.orientation === 'horizontal' ? this.$items.outerWidth(true) : this.$items.outerHeight(true); 
// total width/height of the <ul> 
var totalSpace = this.itemsCount * itemSpace; 
// visible width/height 
var visibleSpace = this.options.orientation === 'horizontal' ? this.$carousel.width() : this.$carousel.height(); 
//slide auto 
window.setInterval(function(){ 
    //test if we should go to next slide or return to first slide 
    if(totalSpace > translation + visibleSpace) 
    { 
     //go to next slide 
     self._slide('next'); 
     //update translation 
     translation += visibleSpace; 
    } 
    else 
    { 
     //return to first slide (infinite loop is too bad for ergonomics) 
     self._slideTo(0); 
     //set translation to 0 
     translation = 0; 
    } 
}, 7000); 
+0

Подтверждено! Это работает, спасибо за потрясающее обновление +1 голос введите код в файл «jquery.elastislide.js» в «_initEvents: function()», сразу после «self = this». – rockit

0

слегка модифицированную версию ответа RoxySka, добавив возможность превратить его включения и выключения с настройками инициализации.

Это сделает автовоспроизведение Elastislide, и когда на последнем слайде оно вернется к первому слайду.

Добавьте этот код в $.Elastislide.defaults объекта после start : 0,:

// autoplay true || false 
autoplay : true, 

Затем вы имеете возможность установить значение autoplay (истина или ложь), если вы установите опции вверх, как вы были пытаясь сделать в вашем примере код выше.

Этот код должен быть добавлен в функции _initEvents после вар self = this;

 if(this.options.autoplay == true){ 
      var translation = 0; 
      // width/height of an item (<li>) 
      var itemSpace = this.options.orientation === 'horizontal' ? this.$items.outerWidth(true) : this.$items.outerHeight(true); 
      // total width/height of the <ul> 
      var totalSpace = this.itemsCount * itemSpace; 
      // visible width/height 
      var visibleSpace = this.options.orientation === 'horizontal' ? this.$carousel.width() : this.$carousel.height(); 
      //slide auto 
      window.setInterval(function(){ 
       //test if we should go to next slide or return to first slide 
       if(totalSpace > translation + visibleSpace) 
       { 
        //go to next slide 
        self._slide('next'); 
        //update translation 
        translation += visibleSpace; 
       } 
       else 
       { 
        //return to first slide 
        self._slideTo(0); 
        //set translation to 0 
        translation = 0; 
       } 
      }, 7000); 
     } 

Имейте в виду, что, как Elastislide эволюционирует прошлое v1.1.0 этот код может не работать в будущих версиях.

0

Это для старой версии elastislide, может быть, этот код может кому-то помочь.

Это не бесконечный цикл, но когда вы дойдете до конца миниатюрной карусели и щелкните дальше, она возвращается с анимацией в исходное состояние, а если вы в начале и нажмите кнопку prev, будет двигаться до последних миниатюр.

Первый Вы должны прокомментировать (или удалить) все строки _toggleControls, таким образом мы избегаем того, чтобы кнопки в навигации скрывались.

А затем изменить код _slide:

 _slide    : function(dir, val, anim, callback) { 

     var ml  = parseFloat(this.$slider.css('margin-left')); 

     // val is just passed when we want an exact value for the margin left (used in the _slideToCurrent function) 
     if(val === undefined) { 

      // how much to slide? 
      var amount = this.fitCount * this.itemW, val; 

      if(amount < 0) return false; 
      // make sure not to leave a space between the last item/first item and the end/beggining of the slider available width 
      if(dir === 'right' && this.sliderW - (Math.abs(ml) + amount) < this.visibleWidth) {     
       amount = this.sliderW - (Math.abs(ml) + this.visibleWidth) - this.options.margin; // decrease the margin left 
       //Loop to the beginning 
       if (amount === 0) { 
        this.current = 0;      
        amount = this.sliderW - this.visibleWidth; 
        anim = undefined; 
        dir = 'left'; 
       } 
      } 
      else if(dir === 'left' && Math.abs(ml) - amount < 0) { 
       amount = Math.abs(ml); 
       //Loop to the end 
       if ($(".es-carousel ul").css("margin-left") === "0px") { 
        this.current = this.itemsCount - 1; 
        amount = -(this.sliderW - this.visibleWidth);      
        anim = undefined; 
       } 
      } 
      else { 
       var fml; // future margin left 
       (dir === 'right') 
        ? fml = Math.abs(ml) + this.options.margin + Math.abs(amount) 
        : fml = Math.abs(ml) - this.options.margin - Math.abs(amount);      
      } 

      (dir === 'right') ? val = '-=' + amount : val = '+=' + amount;     
     } 
     else { 
      var fml  = Math.abs(val); // future margin left 

      if(Math.max(this.sliderW, this.visibleWidth) - fml < this.visibleWidth) { 
       val = - (Math.max(this.sliderW, this.visibleWidth) - this.visibleWidth); 
       if(val !== 0)      
        val += this.options.margin; // decrease the margin left if not on the first position       
       fml = Math.abs(val); 
      } 
     } 

     $.fn.applyStyle = (anim === undefined) ? $.fn.animate : $.fn.css; 

     var sliderCSS = { marginLeft : val }; 

     var instance = this; 

     this.$slider.stop().applyStyle(sliderCSS, $.extend(true, [], { duration : this.options.speed, easing : this.options.easing, complete : function() { 
      if(callback) callback.call(); 
     } })); 

    }, 
Смежные вопросы