Yus*_*liq 13 html javascript random jquery
我有这个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});
});
Run Code Online (Sandbox Code Playgroud)
我试图使顺序随机化,因此div.container div它处于任意位置,意味着它的起始位置不同.div必须保持在div.container
我已经尝试了 http://jsfiddle.net/UgX3u/32/ http://jsfiddle.net/UgX3u/20/以及我在网上找到的更多功能但非工作正常
如何让div以随机顺序显示
use*_*654 13
试试这个:
$("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() );
});
Run Code Online (Sandbox Code Playgroud)
.sort 像这样应用于jQuery:
$.fn.sort = [].sort
Run Code Online (Sandbox Code Playgroud)
由于它不像其他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() );
});
Run Code Online (Sandbox Code Playgroud)
var $container = $("div.container");
$container.html(shuffle($container.children().get()));
function shuffle(o){
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
Run Code Online (Sandbox Code Playgroud)
在这里找到随机播放功能
更新: jsFiddle
| 归档时间: |
|
| 查看次数: |
11629 次 |
| 最近记录: |