jquery找到图像大小并设置为div css的高度和宽度

时间:2015-03-27 15:44:11

标签: javascript jquery html css

我正试图让jquery在猫头鹰旋转木马中找到每张图片的大小(每页8-10张图片)。出于某种原因,在开发者中我回来width 0px, height: 0px

以下是开发人员出现的元素:

<div class="item" style="width: 0px; height: 0px;">
    <img src="url.com/img.jpg" alt="">
</div>

我的jquery:

$('.item').each(function() {
    var $this = $(this),
        w = $this.find('img').width(), 
        h = $this.find('img').height();
    $this.width(w).height(h); 
});

如何管理jquery以在加载时获取图像的大小?

3 个答案:

答案 0 :(得分:2)

您需要在加载所有DOM元素后触发脚本。这也是一个很好的做法。由于您使用的是jQuery,只需使用.ready()事件来激活脚本。

<强> Fiddle Here

以下是代码段,

$(document).ready(function() {
  $('.item').each(function() {
    var $this = $(this),
      pic = $this.find('img');
    if (pic.load) {
      var w = pic.width();
      var h = pic.height();
      $this.width(w).height(h);

    } else {
      return;
    }

  });
  alert("width : " + $('.item').width() + " & height : " + $('.item').height());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="item" style="width: 0px; height: 0px;">
  <img src="http://dummyimage.com/190x100/000/fff.png
" alt="" />
</div>

希望这会有所帮助。 快乐编码:)

<强> UPDATE ::

另一个更新的fiddle here

这一次,我添加了一个虚拟div元素,并为该div提供了item div的高度和宽度。

更新#2 :: 您需要等待至少加载图像,然后才能运行找到图像高度和宽度的脚本并将其应用到父div中。你的情况是“项目”div。因此,如果您想在DOM树中准备好映像但是不想等待整个文档DOM树准备就绪时运行脚本,那么您可以使用jQuery .on("DOMready",".item img",function(){});事件函数来实现。我认为这或多或少像是图像的延迟负载

另一次更新 ::更新了我的答案,考虑到DOM已准备就绪,根据这些jQuery .ready().load() API的参考,可能无法加载图像。

答案 1 :(得分:1)

在查询图像的高度和宽度之前,您需要等到图像加载完毕。

以下是代码段,

$(document).ready(function() {  /* Just added this part */
  $('.item').each(function() {
    var $this = $(this),
      $img = $this.find('img');

      $img.load(function(){
         var w = $this.find('img').width();
         var h = $this.find('img').height();
        alert("width: " + w + " & height: " + h);
        $this.width(w).height(h)
      });

    ;
  });
}); /* Just added this part */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="item" style="width: 0px; height: 0px;">
  <img src="http://dummyimage.com/190x100/000/fff.png
" alt="" />
</div>

Jomery就绪函数在dom准备就绪后触发,而不是在确认图像已加载后触发。https://api.jquery.com/ready/

答案 2 :(得分:0)

示例https://jsfiddle.net/pomfr960/

试试这个:

$('.item').each(function () {
    var $this = $(this);
    var img = $this.find('img');

    if(!img.length) return;

    img[0].onload = function () {
        var w = img.width(),
            h = img.height();
        $this.width(w).height(h);
    }
});