簡體   English   中英

jQuery,隨機div順序

[英]jQuery, random div order

我有這個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以隨機順序顯示

試試這個:

http://jsfiddle.net/UgX3u/33/

$("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方法那樣執行,因此沒有記錄。 這確實意味着它可能會發生變化,但我懷疑它會不會改變。 為避免使用未記錄的方法,您可以這樣做:

http://jsfiddle.net/UgX3u/37/

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() );
});
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;
};

這里找到隨機播放功能

更新: jsFiddle

此示例假定您必須使用已分配給它們的類的頁面上已有的元素:

var classes = [];

// Populate classes array
// e.g., ["yellow", "red", "green", "blue", "pink", "orange", "black", "white"]
$('div.container').children().each(function (i, v) {
    classes.push(v.className);
});

// Assign random color to each div
$('div.container').children().each(function (i, v) {
    var color = Math.floor(Math.random()*classes.length)
    $(v).css({backgroundColor: classes.splice(color,1)});
});

http://jsfiddle.net/UgX3u/40/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM