【问题标题】:jQuery - get tallest image's height, apply other images' height difference to top marginjQuery - 获取最高图像的高度,将其他图像的高度差应用于上边距
【发布时间】:2013-07-02 01:32:48
【问题描述】:

我需要遍历一系列图像(数量未知)并获取最高图像的 outerHeight 值。然后我需要遍历所有其他图像并获取它们的 outerHeight 并从最高的 outerHeight 中减去它,然后将该差异应用于该图像的上边距。最终结果将是所有图像底部对齐,是的,我知道这可以通过 CSS 来完成。这是我目前所做的:

HTML

<ul class="hlist">
    <li>
        <figure>
            <img src="any-size.jpg" />
        </figure>
    </li>
</ul>

jQuery

// This is what I have so far, most likely not right...
function createGrid() {
    var imgs = $('.hlist figure > img');
    var imgHeight = $(this).outerHeight();
    var maxImgHeight = 0;

    imgs.each(function () {
        maxImgHeight = maxImgHeight > imgHeight ? maxImgHeight : imgHeight;
    });
}
createGrid();

所以我认为maxImgHeight 在这一点上应该有最高图像的高度(不确定),但除此之外,我缺乏 JS 技能开始发光。我相信我需要再次遍历图像并针对maxImgHeight 测试每个高度,然后将该差异应用于上边距。

这里的任何帮助都将不胜感激,特别是如果它是一个很好的评论和很好解释的帮助:) 谢谢!

【问题讨论】:

  • 几乎是,诚然。自从发布了该问题以来,我尝试了您答案的不同变体-对于该特定情况,它从未完全奏效。我想我会用更好的代码和描述发布一个新的/更新的问题。

标签: javascript jquery loops each


【解决方案1】:

试试这个:

function createGrid() {
    var imgs = $('.hlist figure > img');
    var maxImgHeight = 0;

    imgs.each(function () {
        var imgHeight = $(this).outerHeight();
        maxImgHeight = maxImgHeight > imgHeight ? maxImgHeight : imgHeight;
    });
    imgs.each(function () {
        var margin = maxImgHeight > $(this).outerHeight() ? (maxImgHeight - $(this).outerHeight()) : 0;
        $(this).css("margin-top", (margin + "px"));
    });
}

第一个each 循环查找最高高度并将其存储在maxImgHeight 中,正如您最初计划的那样。第二个each 循环计算并应用每个图像的边距。条件赋值将导致最高图像的margin-top 为0。

【讨论】:

  • 非常感谢,先生!我现在了解解决方案,这在我的项目中完美
【解决方案2】:
function createGrid() {
    var imgs = $('.hlist figure > img'),
        maxImgHeight = 0;

    imgs.each(function () {
        var imgHeight = $(this).outerHeight(true);
        if (imgHeight > maxImgHeight) {
          maxImgHeight = imgHeight;
        }
    });
    imgs.each(function () {
        this.css('margin-top', (maxHeight - $(this).outerHeight(true)) + "px");
    });
}
createGrid();

【讨论】:

  • 也感谢您回答这个问题!您在我上一个问题中对这部分的修复很接近,但不太正确。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多