jquery move elements into a random order

前端 未结 5 990
难免孤独
难免孤独 2020-12-01 11:23

I am attempting to display a series of images in a random order. However, I do not want any single item to repeat until all items have been shown, so instead of selecting a

5条回答
  •  情书的邮戳
    2020-12-01 12:06

    After much exploration, I decided to take the fisher-yates algorithm and apply it with jquery without requiring cloning, etc.

    $('#tout4 img.img_lg').shuffle();
    
    /*
    * Shuffle jQuery array of elements - see Fisher-Yates algorithm
    */
    jQuery.fn.shuffle = function () {
        var j;
        for (var i = 0; i < this.length; i++) {
            j = Math.floor(Math.random() * this.length);
            $(this[i]).before($(this[j]));
        }
        return this;
    };
    

提交回复
热议问题