简体   繁体   English

每个div获取父级的高度-jQuery方法

[英]Each div get height of parent - jQuery approach

I have this structure: 我有这个结构:

<div class="container" style="height:(variable height)">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
<div class="container" style="height:(variable height)">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
<div class="container" style="height:(variable height)">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

So I need each .box gets the height of the parent .container which has different heights from the other and it varies. 因此,我需要每个.box都获取其父.container的高度,该高度彼此不同,并且各不相同。

I need ONLY jQuery approach, no CSS cause I don't want to use absolute position, table-cell or whatever to do that. 我只需要jQuery方法,不需要CSS,因为我不想使用absolute位置, table-cell或其他任何方式来做到这一点。

Thanks! 谢谢!

You can use the function overload of .height 您可以使用.height函数重载

$('.box').height(function(){
    return $(this).parent().height();
});

If you really must use jQuery: 如果您确实必须使用jQuery:

$('.container').each(function(){
    $(this).children().height($(this).height);
});

JS Fiddle demo . JS小提琴演示

It's worth noting, though, that if height is set on the .container elements then you could simply assign: 但是,值得注意的是,如果在.container元素上设置了height则可以简单地分配:

.box {
    height: 100%;
}

JS Fiddle demo . JS小提琴演示

No special position , or display , properties are required. 不需要特殊的positiondisplay属性。

Incidentally, for a plain JavaScript sollution: 顺便提及,对于普通的JavaScript解决方案:

[].forEach.call(document.querySelectorAll('.container'), function (c) {
    [].forEach.call(c.children, function (b) {
        b.style.height = c.style.height;
    });
});

JS Fiddle demo . JS小提琴演示

References: 参考文献:

$(function(){
  $('.container').each(function(i,e){
    $(this).find('.box').css('height',$(this).height())
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM