0

我有一个图像滑块,我将它们按随机顺序排列,但我意识到其中一个图像不断重复。有什么方法可以防止使用 Math.random() 重复图像吗?

这是我到目前为止所做的:http: //jsfiddle.net/Y4jr6/

<script type="text/javascript" language="javascript">

//switch the landing page background images
function slideSwitch() {
    //set variable active
    var $active = $('#slideshow IMG.active');

    //check if attribute active exists
    if ( $active.length == 0 ) $active = $('#slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('#slideshow IMG:first');

    //throw images in random order
    var $sibs  = $active.siblings();
    var rndNum = Math.floor(Math.random() * $sibs.length );
    var $next  = $( $sibs[rndNum] );

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 7000 );
});

</script>

任何帮助将非常感激!!

4

3 回答 3

3

把它想象成一副纸牌。列出您要显示的所有图像,并在显示后将其从列表中删除(现在您不会选择重复项)。只需确保生成的随机数受当前列表长度的限制。

于 2013-08-05T00:10:20.990 回答
2

一个很好的方法是创建一个包含图像索引的数组(即 0 ... n),对数组进行洗牌,然后在数组中递增。您可以随时重新洗牌,当然,如果您在通过阵列的单次“通过”结束时重新洗牌,您可能会偶然得到重复。

于 2013-08-05T00:10:31.003 回答
2

要实现不会重复的随机顺序,您可以执行以下操作。

在数组中定义图像:

var images = [img1, img2, img3, img4, ...]; //image objects or URLs

现在实现一个自定义排序器,该排序器将随机化该数组:

images.sort(randomize);

function randomize() {
    return 0.5 - Math.random();
}

自定义排序器通过比较 a 和 b 值并根据条件返回 0 等于 < 0 或 > 0。这里我们只返回一个介于 -0.5 和 +0.5 之间的随机值,这意味着项目也将随机排序。

该数组现在是随机的,您可以遍历它,并且知道它不会重复任何图像,直到您重新开始。

于 2013-08-05T01:51:57.417 回答