【问题标题】:How can I retrieve the attributes of images?如何检索图像的属性?
【发布时间】:2009-10-12 12:27:29
【问题描述】:

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

喜欢

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

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

谢谢

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    你可以使用属性

    $("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")
    });
    

    【讨论】:

    • 请注意,如果您想获得没有边框和填充宽度的宽度和高度,请使用 innerWidth() 和 innerHeight()。
    • 我想从检索到的图像宽度中减去 20px。该怎么做??
    【解决方案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 遍历来访问您的图像,为脚本添加了一些速度改进。

    【讨论】:

    • 如果所有图像都在一个部分中,您可以将类名添加到包装器div
    【解决方案3】:

    您有 2 种方法来获取图像的高度/宽度。

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

    http://docs.jquery.com/Attributes/attr

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

    谷歌一下!

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2011-06-07
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多