替换网站上的随机图像

时间:2015-05-24 17:58:10

标签: javascript image random

我的目标是用我的图片列表中的一些随机图片替换开放网站中的一张随机图片。我有这个代码,但它改变了网站上的所有图像,我只需要一个随机而不是全部。你能用它帮我吗?

//Handles all images on page with an interval of time
        handleImages: function (lstImgs, time) {
            $.each($('img'), function (i, item) {
                //Skip if image is already replaced
                if ($.inArray($(item).attr('src'), lstImgs) == -1) {
                    var h = $(item).height();
                    var w = $(item).width();

                    //If image loaded
                    if (h > 0 && w > 0) {

                        self.handleImg(item, lstImgs);
                    }
                    else {
                        //Replace when loaded
                        $(item).load(function () {
                            //Prevent 'infinite' loop
                            if ($.inArray($(item).attr('src'), lstImgs) == -1) {
                                self.handleImg(item, lstImgs);
                            }
                        });
                    }
                }
            });

            //Keep replacing
            if (time > 0) {
                setTimeout(function () { self.handleImages(lstImgs, time); }, time);
            }
        },
        //Replace one image
        handleImg: function (item, lstImgs) {
            $(item).error(function () {
                //Handle broken imgs
                self.handleBrokenImg(item, lstImgs);
            });

            self.setRandomImg(item, lstImgs);
        },
        //Set a random image from lstImgs to item 
        setRandomImg: function (item, lstImgs) {
            var h = $(item).height();
            var w = $(item).width();
            $(item).css('width', w + 'px').css('height', h + 'px');
            $(item).attr('src', lstImgs[Math.floor(Math.random() * lstImgs.length)]);
        },
        //Removed broken image from lstImgs, run handleImg on item
        handleBrokenImg: function (item, lstImgs) {

            var brokenImg = $(item).attr('src');
            var index = lstImgs.indexOf(brokenImg);
            if (index > -1) {
                lstImgs.splice(index, 1);
            }
            self.setRandomImg(item, lstImgs);
        },
    };

    //Run on jQuery ready
    $(function () {

        self.handleImages(self.gitmbImgs, 3000);

    });

    //Set global variable
    $.gitmb = self;

1 个答案:

答案 0 :(得分:0)

$.each($('img')选择所有图片,您只需要一张。

更新

<img src="https://thereisnocavalry.files.wordpress.com/2012/08/fractals-erucolindo3.jpg" alt="some image">

<img src="http://ionamiller.weebly.com/uploads/4/7/9/5/4795680/5133447.jpg?617" alt="some image">

<img src="http://wallpoper.com/images/00/17/31/50/abstract-fractal_00173150.jpg" alt="some image">

<img src="http://www.wussu.com/fractals/images/wd950112.gif" alt="some image">

<img src="http://naperdesign.com/wp-content/uploads/2010/09/fractals_generative.jpg" alt="some image">


$().ready(function() {
    var imagesToReplace = $("img");
    var imagesReplaced  = [];
    var imagesAvailable = [
        "http://www.hdwallpapersn.com/wp-content/uploads/2015/04/Fractal-Pictures-3.jpg",
        "http://fc02.deviantart.net/fs27/f/2008/073/c/e/Fractals_of_the_Ball_by_Hosse7.jpg",
        "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTQKqS8FDvMUcbsUTQj8TIbHg7JSIpvcQqWax9Pq5gZX2BcoVIm",
        "http://www.sgeier.net/fractals/fractals/01/Fire%20and%20Water.jpg",
        "http://www.fractalsciencekit.com/fractals/large/Fractal-Mobius-Dragon-IFS-10.jpg",
        "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQV44vnqHs24LfEEmMPKXojB4whOyBMnQbXghk2kJnkeP90bSR8" 
    ];

    var replaceImage = function() {
         var repl_ind, with_ind, img;
        if ( !imagesAvailable.length ) {
            //loop once all images have been replaced
            imagesAvailable = imagesReplaced.slice();
            imagesReplaced = [];          
         }

         repl_ind = Math.floor( Math.random() * imagesToReplace.length );
         with_ind = Math.floor( Math.random() * imagesAvailable.length );

         img = $(imagesToReplace.get(repl_ind));
         console.log("replacing",img.attr("src"),"with",imagesAvailable[with_ind]);

         imagesReplaced.push( img.attr("src") );
         img.attr("src", imagesAvailable[with_ind] );
         imagesAvailable.splice(with_ind, 1);
         //start timer once image is ready, either instantly or after load
        if ( img.get(0).complete ) { 
            setTimeout(replaceImage, 2000 );
            console.log("complete");
            img.get(0).onload=false;
        } else {
            console.log("onload");
            img.get(0).onload = function() {setTimeout(replaceImage, 1000 );};
        }
    }

    setTimeout(replaceImage, 4000 );
});


img {
    width: 6em;
    padding: 0.4em;
    height: 5em;
}

这是fiddle link