我有这个 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();
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>
最佳答案
一种选择是使用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>
关于javascript - 随机幻灯片仅在超过两张幻灯片时才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57392126/