2013-08-05 57 views
0

我有一个图像滑块,我把它们放入随机的输出顺序,但我意识到,其中一个图像不断重复。有什么办法来防止使用Math.random()重复图像?随机图像生成器,但从来没有重复相同的图像 - Javascript

这是我迄今所做的: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> 

任何帮助将不胜感激!

回答

3

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

+0

你有可能向我展示一个例子吗?因为我没有线索甚至接近 – Elmer

+0

我希望我可以帮助更多,但我的JavaScript/jQuery知识并不是那么棒。尝试在http://jsfiddle.net/上创建一个完整的示例并编辑您的原始问题,然后其他人可以提供帮助。 –

+1

感谢您的帮助! :) – Elmer

2

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

+0

你能告诉我一个例子吗?因为我没有线索甚至接近 – Elmer

+1

您是否搜索“使用Javascript的混洗阵列”?你一定很懒,显然不是。 http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript –

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之间的随机值,这意味着这些项目也会随机排序。

该阵列现在是随机化的,你可以很好地重复它,知道它不会重复任何图像,直到你重新开始。