首页 > 解决方案 > Randomizing slides only works if more than two slides

问题描述

I have this randomize() function to randomize slides in Slick Slider. It works, but in Firefox it only works if there are more than two slides. Can anyone see why that is?

Js:

  $.fn.randomize = function(selector) {
    var $el = selector ? $(this).find(selector) : $(this).children(),
      $pars = $el.parent();

    $pars.each(function() {
      $(this).children(selector).sort(function(chA, chB) {
        if ($(chB).index() !== $(this).children(selector).length - 1) {
          return Math.round(Math.random()) - 0.5;
        }
      }.bind(this)).detach().appendTo(this);
    });
    return this;
  };

  $('.slider').randomize().slick();

Html:

<div class="slider">
  <div>
    <img src="https://kenwheeler.github.io/slick/img/fonz1.png" />
  </div>
  <div>
    <img src="https://kenwheeler.github.io/slick/img/fonz2.png" />
  </div>
  <! -- Uncomment to see it working in FF 
   <div>
    <img src="https://kenwheeler.github.io/slick/img/fonz3.png" />
  </div> -->
</div>

jSFiddle here

标签: javascriptjqueryslick.js

解决方案


One option is to convert the jQuery object into an array using get() Use the shuffle code of this SO answer. And use html to update the parent div

$.fn.randomize = function(selector) {
  var $el = selector ? $(this).find(selector) : $(this).children(),
    $pars = $el.parent(),
    array = $el.get();

  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  $pars.html(array);
  return this;
};

$('.slider').randomize();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div>
    3
  </div>
</div>


推荐阅读