繁体   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