我正在使用以下脚本来显示 div 元素的背景图像。
这个问题是图像很大,每张大约 1MB,而且它们不会很快,因此背景效果可以很平滑。我在 `$(window).load(function () {}); 中包装函数但这没有任何区别。
我怎样才能延迟背景图片下载,以便它只在所有图片都下载完后才开始。
jQuery(function ($) {
var body = $('.hmcarousel');
var backgrounds = new Array(
"url(soml_slider_1.jpg)",
"url(soml_slider_2.jpg)",
"url(soml_slider_3.jpg)",
"url(soml_slider_4.jpg)",
"url(soml_slider_5.jpg)"
);
var current = 0;
function nextBackground() {
body.css(
'background',
backgrounds[current = ++current % backgrounds.length]
);
setTimeout(nextBackground, 5000);
}
setTimeout(nextBackground, 5000);
body.css('background', backgrounds[0]);
});
最佳答案
我相信您问题的答案在 this thread 中.
Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:
$("<img/>")
.load(function() { console.log("image loaded correctly"); })
.error(function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;
关于javascript - 下载所有图像后更改背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28145189/