jQuery Equal Height Divs

gri*_*egs 5 jquery jquery-plugins

如果我有以下标记;

<div id="container">
  <div id="box">
    <div id='sameHeight'>One<br>two<br>three</div>
    <div id='sameHeight'>four</div>
    <div id='sameHeight'>five</div>        
  <div>
  <div id="box">
    <div id='sameHeight'>four</div>
    <div id='sameHeight'>six</div>
    <div id='sameHeight'>seven<br>eight</div>
  <div>
</div>
Run Code Online (Sandbox Code Playgroud)

如何确保标记为"sameHeight"的所有div与其他div中的div相同?

我看了一下equalHeights插件,但是假设并排的所有div都在同一个父节点中.我需要一个可以遍历父母或允许我指定父母的人.

有这样的事情还是我需要写它?

编辑

我似乎在我的解释中引起了一些混乱,所以我希望这会让事情变得清晰起来.

查看新标记,容器是一个简单的盒子.

"盒子"divs并排坐着.

然后每个sameheight div在其父级中位于另一个之下.

我试图解决的问题是让每个相同的高度匹配它的相对高度.

它应该看起来像一个网格我想用w/out使用网格.

我希望这有帮助.

编辑2

到目前为止,我想出的是有更好的方法吗?

function SetHeights() {
    var numLines = $('#container>div:eq(0) .sameHeight').length;

    for (var t = 0; t < numLines; t++) {
        var leftHeight = $('#container>div:eq(0) .sameHeight:eq(' + t + ')').outerHeight();
        var rightHeight = $('#container>div:eq(1) .sameHeight:eq(' + t + ')').outerHeight();

        if (leftHeight > rightHeight) {
            $('#container>div:eq(1) .sameHeight:eq(' + t + ')').css({ height: leftHeight });
        }
        else {
            $('#container>div:eq(0) .sameHeight:eq(' + t + ')').css({ height: rightHeight });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 8

首先,您可能知道只有一个元素应该具有任何一个id属性.所以我已经改变了选择器,好像它们是下面的类的类.即使你可能不关心W3C标准,浏览器或JavaScript API等也可能依赖于这种行为而现在或将来都无法工作.

   $(document).ready(function () {    
        $('div.parentDiv > div').each(function() {

        var $sameHeightChildren = $(this).find('.sameHeight');
        var maxHeight = 0;

        $sameHeightChildren.each(function() {
            maxHeight = Math.max(maxHeight, $(this).outerHeight());
        });

        $sameHeightChildren.css({ height: maxHeight + 'px' });


    });
});
Run Code Online (Sandbox Code Playgroud)

注意:如果你希望它们都是相同的高度,尽管它们是父div,这就是你想要的.

$(document).ready(function () {    
        var $sameHeightDivs = $('.sameHeight');
        var maxHeight = 0;
        $sameHeightDivs.each(function() {

            maxHeight = Math.max(maxHeight, $(this).outerHeight());

        });

        $sameHeightDivs.css({ height: maxHeight + 'px' });
});
Run Code Online (Sandbox Code Playgroud)

这将它们设置为每个父div元素的最高高度.

此外,这个答案可能会显示一些其他选项.

另请注意,如果内部内容再次更改(可能通过JavaScript),您将需要再次调用它,或将其放入setInterval()建议的内容中.