2010-06-06 57 views
3

我有一个1024×768图像jQuery的实际图像diamension

<span class="frame"> 
<img alt="Image" title="Image" src="hD41120CA-7164-11DF-A79E-F4CE462E9D80_Green_Sea_Turtle.jpg"> 
</span> 

和下面CSS设置图像宽度

.frame img{ 
    width:425px; 
} 

而jQuery代码

$('.uploaded_image img').attr("width"); 

返回425

我如何检索实际JavaScipt中的图像宽度1024?

+0

http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome – Adam 2010-06-06 18:25:18

回答

5

我不确定,但我认为所有尺寸相关的功能(如.width())将返回实际宽度,而不是图像的实际宽度。

你可以做什么,是在JavaScript中添加一个新的图像,源设置为您的原始图像的来源,并从中获得宽度。

一个未经考验的例子:

tmp_image = new Image(); 
tmp_image.src = $('.uploaded_image img').attr("src"); 
image_width = tmp_image.width; 
+0

绝对太棒了! – 2010-06-06 19:13:29

1

你必须知道,图像的宽度不提供给浏览器的JavaScript核心,直到图像完全加载。我建议在图像对象的onload事件中获取该图像的宽度。

另一个问题是,你得到你的arent通过节点的属性宽度...

要设置图像的onload事件将是这样的:

$('#imageid').load(function() { 
     $(this).css({ width: "", height: "" }).removeAttr("height").removeAttr("width"); 
     var REAL_WIDTH = this.width; 
}) 

图像的代码:

<span class="frame"> 
<img alt="Image" id="imageid" title="Image" src="http://localhost/zapav/site/assets/questions/D41120CA-7164-11DF-A79E-F4CE462E9D80_Green_Sea_Turtle.jpg"> 
</span> 

而且,我必须说,加载事件不会在缓存图片触发...

1

也许这样的东西将是有用的

对于你不想改变原来的位置或图像的功能。

$(this).clone().removeAttr("width").attr("width"); 
$(this).clone().removeAttr("height").attr("height); 
相关问题