从{0}}检索通过html()加载的width()和height()信息

时间:2013-09-17 14:58:08

标签: jquery html image height width

我的问题如下:我开发了一个脚本,允许用户缩放当前页面上显示的图像。点击后,它会加载$('div#imageBox').html() <div><img>。在下面,我正在检索一些信息,例如加载图像的widthheight

有时它会起作用,有时却不起作用。我知道有一个DOM加载问题,但奇怪的是我无法弄清楚为什么有时它可以工作而它没有。由于<div> 0x19px,它加载<img> 0x0function imageBox(src, legende) { $('DIV#imageBox').empty().fadeIn().html('<div><a href="'+src+'" target="_blank"><img src="'+src+'" /></a></div>'); var marginLeft = $('DIV#imageBox DIV').width() / 2; var marginTop = $('DIV#imageBox DIV').height() / 2; var hauteur = $('DIV#imageBox IMG').height(); var largeur = $('DIV#imageBox IMG').width(); var bottom = $('DIV#imageBox SPAN').height(); //alert(marginLeft+'/'+marginTop+'/'+hauteur+'/'+largeur+'/'+bottom); if(legende) $('DIV#imageBox').find('DIV').append('<span>'+legende+'</span>'); if(largeur > $(window).width()) largeur = $(window).width() * 0.8; if(hauteur > $(window).height()) hauteur = $(window).height() * 0.8; // Récupération des nouvelles valeurs au cas où l'image soit redimensionné car trop grande $('DIV#imageBox IMG').hide().height(hauteur); largeur = $('DIV#imageBox IMG').width(); marginTop = hauteur / 2; marginLeft = largeur / 2; if(!$('DIV#imageBox IMG').is(':animated')) { $('DIV#imageBox IMG').show().height(0).animate({'height': hauteur}, 300); $('DIV#imageBox SPAN').width(0).animate({'width': largeur-10}, 300); } $('DIV#imageBox DIV').css({ 'top': '50%', 'left': '50%', 'marginTop': '-'+(marginTop)+'px', 'marginLeft': '-'+(marginLeft)+'px' }); $('DIV#imageBox SPAN').css('bottom', '-'+bottom+'px'); $('DIV#imageBox SPAN:before').css('top', hauteur); }

这是我的jQuery代码:

{{1}}

如果您有任何疑问,请不要犹豫。我可能没有像我希望的那样清楚。

1 个答案:

答案 0 :(得分:1)

由于您已经拥有图像源,因此使用它来创建图像元素并执行onload事件所需的代码

function imageBox(src, legende) {
   $('DIV#imageBox').empty().fadeIn().html('<div><a href="'+src+'" target="_blank"><img src="'+src+'" /></a></div>');
   var img = document.createElement("img");
   img.onload = function() {
      var imgW = this.width; //Images width
      var imgH = this.height; //Images height
      //Do whatever else is needed
   };
   img.src = src;
   //As suggested by Archer, to trigger load even with cached images
   if (img.complete) $(img).load();
}