jQuery-获取最高图像's的高度,应用其他图像'到上边距的高度差

jQuery - get tallest image's height, apply other images' height difference to top margin

本文关键字:高度 图像 其他 应用 获取 高图像 jQuery-      更新时间:2023-09-26

我需要循环浏览一系列图像(数量未知),并获得最高图像的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测试每个高度,然后将差异应用于上边距。

如果这里有任何帮助,我们将不胜感激,尤其是如果这是一个评论良好、解释良好的帮助:)谢谢!

试试这个:

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中,正如您最初计划的那样。第二CCD_ 5循环计算并应用每个图像的裕度。条件分配将导致最高图像的margin-top为0。

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();