开发者

random image; without repeating?

First off I'm not very familiar with javascript, thus here I am. I have this code for my site to draw a random image. Working from this, how can I make the images not repeat? Thanks in adv! Code:

<script type="text/javascript">  

var banner_list = ['http://i1233.photobuc开发者_Python百科ket.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>


After you display the image splice it out of the array, you can use banner_list.splice(ran, 1);. The arguments are .splice(index, howManyToRemove, howManyToInsert). Inserting is optional, so you can just use splice to start at the index of the image you're displaying and remove one. Make sure not to remove it until you're done referencing it.


You can use Array.splice() as Robert suggest with 2 Arrays. One for unsused and one for used images. Check my 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜