1

我目前有一个旋转背景,可以在加载页面时预加载图像。但是,如果可能的话,我想一次预加载一张图片。

我的代码:

function preload(arrayOfImages) {
        $(arrayOfImages).each(function(){


            $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
        });
    }
    $(document).ready(function () {

    var b = [<? $img = getContents(ROOT."/img/backgrounds/");
            foreach($img as $i)
            {   echo "\"" . $i . "\"";
                if($i != end($img)) echo ",";
            }
        ?>];
    preload(b);

    var r=Math.floor(Math.random()*b.length)
    $('#bg1').css("background-image", "url('/img/backgrounds/"+b[r]+"')");

    var alt = false;
    var delay = 50000;
    var speed = ((delay / 3)*2);
    var opacity = 1;

    setInterval(function() {
        var r=Math.floor(Math.random()*b.length);

        //put the individual preload code here

        switch(alt)
        {   case true:
                $('#bg1').css("background-image", "url('/img/backgrounds/"+b[r]+"')");
                $('#bg1').fadeTo(speed,opacity);
                $('#bg2').fadeOut(speed);
            break;
            case false:
                $('#bg2').css("background-image", "url('/img/backgrounds/"+b[r]+"')");
                $('#bg2').fadeTo(speed,opacity);
                $('#bg1').fadeOut(speed);
            break;
        }
        alt = !alt;
        }, delay);

    });

上面的代码工作正常。如果有更好的方法请告诉我!但否则我怎么能一次只预加载一张图片呢?

4

1 回答 1

2
function preload(arrayOfImages, index) {
    index = index || 0;

    if (arrayOfImages && arrayOfImages.length > index) {
        var img = new Image();
        img.onload = function() {
            console.log(arrayOfImages[index] + " loaded successfully");
            preload(arrayOfImages, index + 1);
        };
        img.src = arrayOfImages[index];
    }
}

小提琴

于 2013-01-25T13:24:19.190 回答