获取动态图像的宽度和高度

我有一个嵌入隐藏div的img标签。 当用户点击具有图像名称的动态超链接时,必须在模态窗口中显示图像。 要将div定位在模态窗口内,需要图像高度。 但是当单击超链接时,在分配src之后,高度将变为0.因此图像不能在中间对齐。 请帮助我在浏览器显示之前获取图像的宽度。

 function ShowImage(imgSrc) { $("#imgFull").attr("src", imgSrc); alert($("#imgFull").height()); $("#imgFullView").width($("#imgFull").width()); $("#imgFullView").height($("#imgFull").height()); show_modal('imgFullView', true); } 

这个showimage方法将被称为onclick超链接。 提前致谢…

解决方案对我有用,毕竟你的专业指导……

  function ShowImage(imgSrc) { $("#imgFull").removeAttr("src"); //To remove the height and width of previously showed imaged from img tag. $("#imgFull").attr("src", imgSrc); $("#imgFullView").width(document.getElementById("imgFull").width); $("#imgFullView").height(document.getElementById("imgFull").height); show_modal('imgFullView', true); } 

试试这个。

  var img = $("imgFull")[0]; // Get my img elem var real_width, real_height; $("") // Make in memory copy of image to avoid css issues .attr("src", $(imgFull).attr("src")) .load(function() { real_width = this.width; // Note: $(this).width() will not real_height = this.height; // work for in memory images. }); 

谢谢。

嗯,问题是你无法知道尚未加载的图像的大小。 试试这个:

 function ShowImage(imgSrc) { $("#imgFull").attr("src", imgSrc); $("#imgFull").load(function(){ //This ensures image finishes loading alert($("#imgFull").height()); $("#imgFullView").width($("#imgFull").width()); $("#imgFullView").height($("#imgFull").height()); show_modal('imgFullView', true); }); } 

使用.load()我们确保图像在尝试获取其大小之前完成加载()

希望这可以帮助。 干杯

这在过去对我有用:

 function ShowImage(imgSrc){ $('').bind('load', function(){ if ( !this.complete || this.naturalWidth == 0 ) { $( this ).trigger('load'); } else { $( this ).appendTo('#imgFullView') $('#imgFullView').width(this.naturalWidth).height(this.naturalHeight); } }).attr("src",imgSrc); } $(document).ready(function(){ ShowImage('http://sofzh.miximages.com/jquery/ps_logo2.png') }); 

在这里演示:

http://jsfiddle.net/jyVFc/4/