Owl Carousel 2 random function

前端 未结 2 1848
刺人心
刺人心 2021-01-04 22:42

Is there a way in Owl Carousel 2 make a king random function. I need the slides on the page to load randomly.

Before in the older Owl Carousel version I did it this

相关标签:
2条回答
  • 2021-01-04 23:16

    You have to use the new onInitialize callback, like this:

    var owl = $('.owl-carousel');
    owl.owlCarousel({
        onInitialize : function(element){
            owl.children().sort(function(){
                return Math.round(Math.random()) - 0.5;
            }).each(function(){
                $(this).appendTo(owl);
            });
        },
    });
    

    Find more information in the 2.x docs.

    0 讨论(0)
  • 2021-01-04 23:19

    For some reason, AdmireNL's answer was giving me problems for iOS devices but worked perfectly for everything else. No idea why that would be, but I solved my issue by using the top answer listed here: How to randomly sort list items?

    My final code:

    $.fn.randomize = function(selector){
      var $elems = selector ? $(this).find(selector) : $(this).children(),
      $parents = $elems.parent();
    
      $parents.each(function(){
        $(this).children(selector).sort(function(){
            return Math.round(Math.random()) - 0.5;
        }).detach().appendTo(this);
      });
    
      return this;
    };
    
    var slider = $('#slider');
    slider.owlCarousel({
        onInitialize : function(){
            $(slider).randomize();
        }
    });
    
    0 讨论(0)
提交回复
热议问题