【问题标题】:Combined width of images applied to div - not working when images have padding应用于 div 的图像的组合宽度 - 当图像有填充时不起作用
【发布时间】:2011-02-08 11:11:03
【问题描述】:

我需要获取 div 内图像的组合宽度并将该宽度应用于 div。我从这里使用此代码:

Take combined width of multiple images and apply to their containing div

$(document).ready(function() {
    $('div').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
          totalImageWidth += $(this).width();
        });

        $(this).width(totalImageWidth);
    });
});

在我对图像应用填充之前,这可以正常工作。然后包含的 div 太小,因为图像占用了更多空间。

为了尝试解决这个问题,我将“img”更改为包含图像的 div。所以这: ("img", this) 变为:("div-which-is-around-image", this)

由于某种原因,现在包含的 div 太宽了。我不知道为什么会这样。如果问题是图像没有及时加载,我将 dom 更改为窗口加载,但这没有区别。

谢谢

【问题讨论】:

  • 你能发布你的 HTML 和 CSS 吗?
  • 请添加您所说的 HTML 和 CSS 代码。您是否将填充应用于图像或包含图像的 DIV?
  • 好像没问题。您可以发布您应用填充或更多的代码吗?

标签: jquery width


【解决方案1】:

您可以使用innerWidth() 方法代替width() 返回包含填充的宽度(不包括边框和边距) 您的代码应如下所示:

$(document).ready(function() {
    $('div').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
          totalImageWidth += $(this).innerWidth();
        });

        $(this).width(totalImageWidth);
    });
});

【讨论】:

    【解决方案2】:

    糟糕,我将图像向左浮动,但不是它的 div。浮动它们都解决了这个问题。 谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 2011-04-09
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      相关资源
      最近更新 更多