如何检索图像的属性?

Was*_*ikh 0 html javascript css jquery

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

喜欢

<div class=top>&nbsp;</div>
<img src="source.jpg" width="200" height="400" alt="" />
<div class="bottom">&nbsp</div>
Run Code Online (Sandbox Code Playgroud)

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

谢谢

jan*_*mon 8

您可以使用这些属性

$("img[src=source.jpg]").attr("width");
$("img[src=source.jpg]").attr("height");
Run Code Online (Sandbox Code Playgroud)

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

 $("img[src=source.jpg]").width();
 $("img[src=source.jpg]").height(); 
Run Code Online (Sandbox Code Playgroud)

编辑(修改你的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")
});
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,如果要获得没有边框和填充宽度的宽度和高度,请使用innerWidth()和innerHeight(). (3认同)