我目前有一个旋转背景,可在页面加载时预加载图像。但是,如果可能的话,我想一次预加载一个图像。
我的代码:
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);
});
上面的代码运行正常。如果有更好的方法请告诉我!但是否则我怎样才能一次预加载一个图像?
答案 0 :(得分: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];
}
}