[英]How to know when all images inside a specific “div” are loaded?
我的HTML頁面的一部分是以下div
:
<div id="images_wrapper">
<img ... />
<img ... />
<img ... />
...
</div>
最初,這個div
是隱藏的,我只在加載所有圖像時顯示它:
$(window).load(show_images_wrapper);
但是,如果我沒有弄錯,只有在加載所有頁面時才會調用show_images_wrapper
。 我希望show_images_wrapper
加載了images_wrapper
所有圖像,就會調用images_wrapper
,並且不要等到所有頁面都加載images_wrapper
。
我試過了:
$("#images_wrapper").load(show_images_wrapper);
但它不起作用。
我該怎么做?
property, that is decremented as the images load. 使用length
屬性設置計數器數量的計數器,該屬性在圖像加載時遞減。
var imgs = $("#images_wrapper > img").not(function() { return this.complete; });
var count = imgs.length;
if (count) {
imgs.load(function() {
count--;
if (!count) {
$("#images_wrapper").show();
alert('all done');
}
});
} else {
$("#images_wrapper").show();
}
method is removing from the matched set the images where their .complete
property is true
. not()
方法是從匹配的集合中刪除其.complete
屬性為true
的圖像。 這意味着圖像已經下載,並且可能是由瀏覽器緩存的。
method fires as each image finishes loading. 當然, load()
方法會在每個圖像完成加載時觸發。
示例: http : //jsfiddle.net/uhmAR/1/
編輯:更改它,以便容器將顯示是否所有圖像都被緩存。
編輯:
method to get the ones that are .complete
, and just manually invoke the .load()
on them. 上面的另一個變體是將.load()
綁定到所有圖像,並使用filter()
方法獲取.complete
,然后手動調用它們上的.load()
。
這消除了對if/else
語句的需要。
var imgs = $("#images_wrapper > img")
var count = imgs.length;
imgs.load(function() {
count--;
if (!count) {
$("#images_wrapper").show();
alert('all done');
}
}).filter(function() { return this.complete; }).load();
示例: http : //jsfiddle.net/uhmAR/3/
我寫了一個jQuery插件 ,可以做到這一點。
$('#images_wrapper').waitForImages(function() {
// Done.
});
或者,
var images = $('#images_wrapper img'),
imagesLength = images.length;
images.load(function() {
if ( ! --imagesLength) {
// Done.
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.