开发者

Resizing Images In Jquery Soon After Adding To The DOM?

I'm doing something like this:

maxDim = 100;
$('div.images').html('<img class="pull" src="'+imgs[img_i]+'" />');
$('img.pull').each(function(i){
  if( $(th开发者_运维知识库is).height() > $(this).width() ){
    var h = maxDim;
    var w = Math.ceil( $(this).width() / $(this).height() * maxDim);
  }
  else{
    var w = maxDim;
    var h = Math.ceil( $(this).height() / $(this).width() * maxDim);
  }
  $(this).css({height:h, width:w});
});

Now I'm pretty sure that the image resizing part is just fine ... esp since it matches up with this answer http://adeelejaz.com/blog/resize-images-on-fly-using-jquery/

The problem that sometimes it works, sometimes it doesn't. (it will show up still native resolution at times and resized on others) It seems that timing is the real issue here. Maybe the resizing gets called before the image is actually in the DOM to select it again right after? Any advice you guys have would be greatly appreciated.


I guess the images are not loaded yet sometimes. In that case the original size is still unknown (0) and the calculation leads onto NaN-values because of division by zero.

Resizing when the load-event of the images fires should be an option.


You will need the special image load event plug-in. Otherwise, the event will not fire if the image is already in the browser's cache. Then you can do this:

$('img.pull').load(function(i){
    // ...
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜