我排成几列。当我刷新页面时,有没有办法随jQuery随机改变它们的顺序?
<div class="container">
<div class="row">
<div class="col-xs-6">1</div>
<div class="col-xs-6">2</div>
<div class="col-xs-6">3</div>
<div class="col-xs-6">4</div>
<div class="col-xs-6">5</div>
<div class="col-xs-6">6</div>
<div class="col-xs-6">7</div>
<div class="col-xs-6">8</div>
<div class="col-xs-6">9</div>
<div class="col-xs-6">10</div>
</div>
</div>
答案 0 :(得分:0)
您可以使用jquery。由于您还没有提供示例代码,或向我们展示您的努力,我已经准备好了自己的小提琴。
检查此代码段:
/**
* Returns a random integer between min and max values (inclusive)
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Returns a uniquely generated random integer array, so we can use this as our order.
*/
function getRandomSequence(limit) {
var arr = [];
while (arr.length < limit) {
var randomnumber = getRandomInt(0, limit - 1);
var found = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == randomnumber) {
found = true;
break;
}
}
if (!found) arr[arr.length] = randomnumber;
}
return arr;
}
/**
* Shows randomly ordered columns in a container.
*/
function orderColumnsRandomly() {
// Get the children of the container
var columns = $("#xcontainer").children();
// Empty the container.
$("#xcontainer").html('');
// Get a random sequence to show the columns
var sequence = getRandomSequence(columns.length);
// Loop through the column array with the given sequence and fill the container.
for (var i = 0; i < sequence.length; i++) {
$("#xcontainer").append($(columns[sequence[i]]));
}
}
// Bind the button's click event.
$("#orderRandomly").click(orderColumnsRandomly);
&#13;
.column {
padding: 15px;
color: white;
text-align: center;
}
.a {
background: #c33
}
.b {
background: #3c3
}
.c {
background: #33c
}
.d {
background: #3cc
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="row">
<div class="col-lg-12">
<button id="orderRandomly">Order!</button>
</div>
</div>
<br>
<div class="row" id="xcontainer">
<div class="column col-xs-3 a">a</div>
<div class="column col-xs-3 b">b</div>
<div class="column col-xs-3 c">c</div>
<div class="column col-xs-3 d">d</div>
</div>
</div>
&#13;
我们只是生成一个随机整数数组,并使用该随机序列,我们用我们的div填充容器。
答案 1 :(得分:0)
这个有效:
$.fn.randomize = function(childElem) {
return this.each(function() {
var $this = $(this);
var elems = $this.children(childElem);
elems.sort(function() { return (Math.round(Math.random())-0.5); });
$this.remove(childElem);
for(var i=0; i < elems.length; i++)
$this.append(elems[i]);
});
}
$(".xcontainer").randomize(".column");