我有这个 jQuery 和 HTML http://jsfiddle.net/UgX3u/30/
<div class="container">
<div class="yellow"></div>
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
<div class="pink"></div>
<div class="orange"></div>
<div class="black"></div>
<div class="white"></div>
</div>
$("div.container div").each(function(){
var color = $(this).attr("class");
$(this).css({backgroundColor: color});
});
我正在尝试随机化顺序,因此 div.container div
处于任意随机位置,这意味着它开始的位置不同。并且 div 必须保留在 div.container
我试过了 http://jsfiddle.net/UgX3u/32/ http://jsfiddle.net/UgX3u/20/还有更多我在网上找到但无法使用的功能
如何让 div 以随机顺序显示
最佳答案
试试这个:
$("div.container div").sort(function(){
return Math.random()*10 > 5 ? 1 : -1;
}).each(function(){
var $t = $(this),
color = $t.attr("class");
$t.css({backgroundColor: color}).appendTo( $t.parent() );
});
.sort
像这样应用于 jQuery:
$.fn.sort = [].sort
因为它不像其他 jQuery 方法那样执行,所以没有记录。这确实意味着它可能会发生变化,但我怀疑它永远不会改变。为避免使用未记录的方法,您可以这样做:
var collection = $("div.container div").get();
collection.sort(function() {
return Math.random()*10 > 5 ? 1 : -1;
});
$.each(collection,function(i,el) {
var color = this.className,
$el = $(el);
$el.css({backgroundColor: color}).appendTo( $el.parent() );
});
关于javascript - jQuery,随机div顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9436360/