如何检索图像的属性?

时间:2009-10-12 12:27:30

标签: javascript jquery html css

如何使用jQuery从IMG标记中检索图像高度和宽度,并在div样式中使用此值。

喜欢

<div class=top>&nbsp;</div>
<img src="source.jpg" width="200" height="400" alt="" />
<div class="bottom">&nbsp</div>

我想使用Image的高度并应用于DIV。 像400px-20px。 div宽度。

感谢

3 个答案:

答案 0 :(得分:8)

您可以使用属性

$("img[src=source.jpg]").attr("width");
$("img[src=source.jpg]").attr("height");

或者您可以使用维度方法(它们由jQuery计算):

 $("img[src=source.jpg]").width();
 $("img[src=source.jpg]").height(); 

编辑(修改你的div)

$("div.top").add("div.bottom").css({ 
      width: $("img[src=source.jpg]").attr("width") - 20,//<- your minus 20 goes here
      height: $("img[src=source.jpg]").attr("height")
});

答案 1 :(得分:2)

您应该为图片标记添加一个类名,以便使用jQuery更容易访问它:

<img src="source.jpg" class="yourClassHere" width="200" height="400" alt="" />

然后,您将能够直接访问该特定图像的高度和宽度,而不能直接访问页面上的任何其他图像。这是完整示例,在文档准备好后执行操作。

$(function() {
    var $img = $('img.yourClassHere');
    $('.top, .bottom').css({ height: $img.attr('height'), width: $img.attr('width') }); 
});

我还通过减少DOM遍历来访问您的图像,为脚本添加了一些速度改进。

答案 2 :(得分:1)

您有2种方法可以获得图像的高度/宽度。

1)var height = $("img").attr("height");

请参阅http://docs.jquery.com/Attributes/attr

2)var height = $("img").height();

GOOGLE IT!

相关问题