我在我的网站上使用此代码来随机化 div 的顺序。在我的一个子页面上,我想在稍作修改的版本中使用它 - 将再次以随机顺序显示 12 个 div,但只会显示前 3 个,其余将设置为“display:none;”或者用js实现类似的效果。
有什么建议可以修改下面的代码,以便只显示前 3 个 div 吗?
这是代码:http://jsfiddle.net/ca7WW/
HTML:
<div class="randomize">
<div class="random_div">1</div>
<div class="random_div">2</div>
<div class="random_div">3</div>
<div class="random_div">4</div>
<div class="random_div">5</div>
<div class="random_div">6</div>
<div class="random_div">7</div>
<div class="random_div">8</div>
<div class="random_div">9</div>
<div class="random_div">10</div>
<div class="random_div">11</div>
<div class="random_div">12</div>
</div>
jQuery:
function shuffle(array) {
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;
}
return array;
}
(function ($) {
$.fn.randomize = function (childElem) {
return this.each(function () {
var $this = $(this);
var elems = shuffle($(childElem));
$this.remove(childElem);
for (var i = 0; i < elems.length; i++)
$this.append(elems[i]);
});
}
})(jQuery)
jQuery(function($){
$("div.randomize").randomize("div.random_div");
});
最佳答案
使用 :lt
和 :gt
获取选择器中的“前 N 个”或“后 N 个”元素。
jQuery(function($){
$("div.randomize").randomize("div.random_div");
$(".random_div:gt(2)").hide(); // This hides anything after the 3rd element
});
关于javascript - 随机div,只显示其中的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253417/