簡體   English   中英

在加載/選擇時隨機化圖庫

[英]randomize image gallery on load/selection

這是我的第一個問題,因此對任何格式問題,由於無知而遺漏或過度解釋我深表歉意。 我幾乎對Java語言完全陌生,經過一天的嘗試修改后,我決定尋求幫助。

當前:我有一個無序列表,用作選擇器以顯示與其關聯的畫廊。 我正在嘗試做的是修改下面的代碼,以使圖像以隨機順序加載,而不是默認順序(按上次添加的順序加載)。 我一直在嘗試使用Fisher Yates方法,但是我要么實現錯誤,要么感到困惑。 任何幫助將不勝感激,並感謝您抽出寶貴的時間閱讀本文。

 $('#artist-list li').click(function(event){
    event.preventDefault();
    var artist = $(this).attr('data-artist');

    // Highlight selected menu item
    $('#artist-list li').removeClass('active');
    $(this).addClass('active');

    // Show selected artist bio
    $('.artist-bio, .artist-image').hide();
    $('#artist-'+artist+', #artist-image-'+artist).show();

    $('#image-list li').not('.primary').hide();
    $('#image-list li.'+artist).show().children('a').attr('rel', artist);
}); // End click

$('#artist-list.departments li').click(function(event){
    event.preventDefault();
    var artist = $(this).attr('data-dept');

    // Highlight selected menu item
    $('#artist-list li').removeClass('active');
    $(this).addClass('active');

    // Show selected artist bio
    $('.artist-bio, .artist-image').hide();
    $('#artist-'+artist+', #artist-image-'+artist).show();

    $('#image-list li').not('.primary').hide();
    $('#image-list li.'+artist).show().children('a').attr('rel', artist);
}); // End click

我發現這個有用的小插件可以為您整理列表:

(function($){

    $.fn.shuffle = function() {

        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });

        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });

        return $(shuffled);

    };

})(jQuery);

並在列表中進行操作,如下所示:

<ul id="gallery">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

稱它為:

$('#gallery li').shuffle();

jsFiddle: http : //jsfiddle.net/hescano/4XFQr/

資料來源: http : //css-tricks.com/snippets/jquery/shuffle-dom-elements/

暫無
暫無

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

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