最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i know if all <img> loaded in div using jQuery - Stack Overflow

programmeradmin5浏览0评论

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);

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);
Share Improve this question edited Sep 23, 2010 at 22:26 Yi Jiang 50.2k16 gold badges139 silver badges136 bronze badges asked Sep 23, 2010 at 22:12 faressoftfaressoft 19.7k44 gold badges107 silver badges149 bronze badges 2
  • 1 possible duplicate of Official way to ask jQuery wait for all images to load before executing something – Peter Ajtai Commented Sep 23, 2010 at 22:28
  • $(window).load this can help me if i want to know when all images in page loaded :) but i want not that. – faressoft Commented Sep 23, 2010 at 22:38
Add a ment  | 

2 Answers 2

Reset to default 9

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
      // ...
    }
  }
}());
发布评论

评论列表(0)

  1. 暂无评论