我有一个三列布局,每列都有多个包含相似内容 block 的 div:
<section class="info-blocks-container clearfix">
<div id="col1">
<div class="info-block">...</div>
<div class="info-block">...</div>
<div class="info-block">...</div>
</div>
<div id="col2">
<div class="info-block">...</div>
<div class="info-block">...</div>
</div>
<div id="col3">
<div class="info-block">...</div>
<div class="info-block">...</div>
<div class="info-block">...</div>
</div>
</section>
我想在列中随机排列 div#col1
、div#col2
和 div#col3
中的子 div ,因此 #col1
的某些子 div 最终会出现在 #col2
和/或 #col3
中,反之亦然。我正在使用 codeparadox 的 function reorder()
发现 here (我删除了“撤消”功能)并且洗牌正在工作,但是
1.我有3个独立的重复函数的方式非常脏,并且
2.它仅对每列中的 div 进行排序(它不会在三列之间共享子 div):
<script type="text/javascript">
$(function(){
reorder();
reorder2();
reorder3();
function reorder() {
var grp = $(".info-blocks-container > div:nth-child(1)").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$(".info-blocks-container > div:nth-child(1)").append($(grp));
}
function reorder2() {
var grp = $(".info-blocks-container > div:nth-child(2)").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$(".info-blocks-container > div:nth-child(2)").append($(grp));
}
function reorder3() {
var grp = $(".info-blocks-container > div:nth-child(3)").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$(".info-blocks-container > div:nth-child(3)").append($(grp));
}
});
</script>
有什么建议吗?
最佳答案
其次,你的问题对我来说确实是一个挑战。但我想我找到了一个解决方案:
var columnsCollection = new Array();
var columnsObjectsNumber = new Array();
reorder();
function reorder() {
$(".info-blocks-container").find("DIV[id^='col']").each(function()
{
var tmp = $(this).children();
//Store the numbers of contained children
columnsObjectsNumber.push($(tmp).size());
$(tmp).each(function()
{
//transfers current child object to our global store place
columnsCollection.push($(this));
//and removed it
$(this).remove();
});
});
var restartIndex = 0;
$(".info-blocks-container").find("DIV[id^='col']").each(function()
{
//Contains the random generated number
var x;
//Contains the current object with Id 'col..'
var temp = $(this);
for (var i = 0; i < columnsObjectsNumber[restartIndex]; i++)
{
/*
Generates a random number.
The maximum limit is the current length from our global store place
*/
x = Math.floor(Math.random() * columnsCollection.length);
//Appends the object to the current object with Id 'col..'
$(temp).append(columnsCollection[x]);
//Removes the appended element from global store place
columnsCollection.splice(x,1);
}
restartIndex++;
});
}
它看起来不专业,但很有效。希望这是您所要求的...
关于Jquery 在多列中随机/随机播放内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12313928/