随机图像;不重复?

时间:2011-02-01 04:31:34

标签: javascript jquery jquery-plugins

首先我对javascript不太熟悉,因此我就是这样。 我有这个代码为我的网站绘制一个随机图像。通过这种方式,我怎样才能使图像不重复?谢谢你!代码:

<script type="text/javascript">  

var banner_list = ['http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/LM_LogoMark4-4-2.gif',   'http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/logobg_dome.png',  'http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/logobg_brain.png'];    $(document).ready(function() { var ran = Math.floor(Math.random()*banner_list.length);
$(".logobg img").attr(banner_list[ran]);
});  $(document).bind("projectLoadComplete", function(e, pid){
var ran = Math.floor(Math.random()*banner_list.length);
$(".logobg img").attr("src", banner_list[ran]);
}); </script>

2 个答案:

答案 0 :(得分:0)

显示图像后,将其拼接出阵列,您可以使用banner_list.splice(ran, 1);。参数是.splice(index, howManyToRemove, howManyToInsert)。插入是可选的,因此您可以使用splice从您正在显示的图像的索引处开始并删除一个。确保在完成参考之后不要删除它。

答案 1 :(得分:0)

您可以使用Array.splice()作为Robert建议2阵列。一个用于未使用,一个用于已用图像。检查我的JSfiddle

var images = ["http://www.fowkesauto.com/products_pictures/nutsbolt.jpg",
              "http://i01.i.aliimg.com/photo/v0/114511763/Fasteners_Bolts_and_Nuts.jpg",
              "http://us.123rf.com/400wm/400/400/DLeonis/DLeonis0810/DLeonis081000018/3706757-bolts-and-nuts-on-white.jpg",
              "http://static3.depositphotos.com/1003288/173/i/950/depositphotos_1737203-Nuts-and-bolts.jpg"],
    usedImages = [];

setInterval(function () {changeImage();},500);

var changeImage = function () {
    var index = Math.floor(Math.random() * (images.length)),
        thisImage = images[index];

        usedImages.push(thisImage);
        images.splice(index, 1);

        if (images.length < 1) {
            images = usedImages.splice(0, usedImages.length);
        }

        $("#image").attr("src", thisImage);
}
相关问题