How can i know if all <img> loaded in div using jQuery
How can i know if all loaded in div using jQuery
i want to do this after load all img in #slider div
var imgHeight开发者_高级运维 = $("#slider img").height();
alert(imgHeight);
You can use the load
event
$('#slider img').load(function(){
var imgHeight = $(this).height();
alert(imgHeight);
});
if there are more than one image, and you only want to obtain the height after they have all loaded, try this code
var img = $('#slider img');
var length = img.length;
img.load(function(){
length--;
if(length === 0){
alert("All images loaded");
};
});
Well, I've tested the code, and it appears that the problem hasn't got anything to do with the code. When loading the page with the images already in the cache, this is what I get:
Strangely, this does not occur when I force the browser not to use the cache.
Try this:
- Attach an
onload
event listener to each image in the slider. - In the listener:
- Give the current image a custom attribute to mark it is 'ready'.
- Check if all images are ready. If so, do your thing (i.e.
alert(imageHeight)
)
untested:
(function(){
var slider=document.getElementById('slider'),
images=slider.getElementsByTagName('img'), image, i=-1;
while (image=images[i]) {
image.onload=function(){
this['data-ready']=true;
var image, i=-1;
while (image=images[i]) if (!image['data-ready']) return;
// all images are ready; do your thing here
// ...
}
}
}());
精彩评论