我正在向页面添加一些用于幻灯片放映的大图像,但我想仅在页面的正常部分完全加载(包括图像)时才开始加载这些图像。
为此,我将图像添加到 $(window).load()
函数中:
var slide_total = 20;
$(window).load(function() {
for (i = 2; i <= slide_total; i++)
{
content = '<li><img src="/images/header' + ((i < 10) ? '0' : '') + i + '.jpg" width="960" height="314"></li>';
$("#slideshow li:last-child").after(content);
}
slide_interval = setInterval( "slideSwitch()", slide_duration );
});
幻灯片放映 slideSwitch()
应该在所有图像完全加载时开始,但就像现在一样,它在元素添加到 DOM 时开始。
我无法将循环移至 document.ready
函数,因为我不希望幻灯片放映干扰正常图像的加载。
如何在设置间隔之前检查是否所有图像都已加载?
最佳答案
试试这个:
// get the total number of images inserted in the DOM
var imgCount = $('#slideshow img').length;
// initialize a counter which increments whenever an image finishes loading
var loadCounter = 0;
// bind to the images' load event
$("#slideshow li img").load(function() {
// increment the load counter
loadCounter++;
// once the load counter equals the total number of images
// set off the fancy stuff
if(loadCounter == imgCount) {
slide_interval = setInterval( "slideSwitch()", slide_duration );
}
}).each(function() {
// trigger the load event in case the image has been cached by the browser
if(this.complete) $(this).trigger('load');
});
关于jquery - 在继续之前验证所有图像是否已加载到 `$(window).load()` 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3669017/