[英]Randomizing slides only works if more than two slides
我有这个 randomize() 函数来随机化 Slick Slider 中的幻灯片。 它有效,但在 Firefox 中,它仅在有两张以上的幻灯片时才有效。 谁能看出这是为什么?
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();
网址:
<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>
一种选择是使用get()
将jQuery
对象转换为数组 使用此SO answer的随机播放代码。 并使用html
更新父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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.