在多个div上随机化背景图像,而不显示相同的图像



我在一个页面上得到了3-4个div,每次加载页面时我都想随机化一个图像列表。在下面的例子中,这很好,但我发现有时你可能会得到3个相同的图像或两个相同的图片。有没有一个大的逻辑可以用来避免这种情况?

HTML

<div class="wrap">
  <div class="divide-img"></div>
  <div class="divide-img"></div>
  <div class="divide-img"></div>
</div>

jQuery:

$(document).ready(function() {
    var images = ['http://lorempixel.com/400/200/sports/1', 'http://lorempixel.com/400/200/sports/2', 'http://lorempixel.com/400/200/sports/3', 'http://lorempixel.com/400/200/sports/4'];
    $('.divide-img').each(function(){
        $(this).css({'background-image': 'url(' + images[Math.floor(Math.random() * images.length)] + ')'});  
    });
}); 

如有任何帮助/指导,我们将不胜感激。

工作示例的链接

与您的方法不同,我会首先对图片的初始数组进行混洗,然后将图片分配给div,以便它们在混洗数组中出现。

在javascript中快速搜索shuffle方法后,我发现了一篇帖子(How can I shuffle an array?),展示了如何创建这样的函数

function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

现在,一旦你有了shuffle方法,你的实现可能看起来像这个

$(document).ready(function() {
    var images = ['http://lorempixel.com/400/200/sports/1', 'http://lorempixel.com/400/200/sports/2', 'http://lorempixel.com/400/200/sports/3', 'http://lorempixel.com/400/200/sports/4'];
    images = shuffle(images);
    $('.divide-img').each(function(i){
        $(this).css({'background-image': 'url(' + images[i] + ')'});  
    });
}); 

您需要随机化数组中元素的顺序,然后通过它循环。

检查如何随机化(搅乱)JavaScript数组?关于如何随机化数组。

您需要删除已使用的图像:

 $('.divide-img').each(function(){
      var rnd = Math.floor(Math.random() * images.length)
        $(this).css({'background-image': 'url(' + images[rnd] + ')'}); 
      images.splice(rnd, 1)
    });

您可以在使用图像时将其删除。

$(document).ready(function() {
    var images = ['http://lorempixel.com/400/200/sports/1', 'http://lorempixel.com/400/200/sports/2', 'http://lorempixel.com/400/200/sports/3', 'http://lorempixel.com/400/200/sports/4'];
    $('.divide-img').each(function(){
        var index = Math.floor(Math.random() * images.length)
        $(this).css({'background-image': 'url(' + images[index] + ')'});
        images.splice(index);
    });
}); 

最新更新