![](/img/trans.png)
[英]Get the height of a DIV where the parent DIV has position absolute (JQuery)
[英]Each div get height of parent - jQuery approach
我有这个结构:
<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>
因此,我需要每个.box
都获取其父.container
的高度,该高度彼此不同,并且各不相同。
我只需要jQuery方法,不需要CSS,因为我不想使用absolute
位置, table-cell
或其他任何方式来做到这一点。
谢谢!
您可以使用.height
函数重载
$('.box').height(function(){
return $(this).parent().height();
});
如果您确实必须使用jQuery:
$('.container').each(function(){
$(this).children().height($(this).height);
});
JS小提琴演示 。
但是,值得注意的是,如果在.container
元素上设置了height
则可以简单地分配:
.box {
height: 100%;
}
JS小提琴演示 。
不需要特殊的position
或display
属性。
顺便提及,对于普通的JavaScript解决方案:
[].forEach.call(document.querySelectorAll('.container'), function (c) {
[].forEach.call(c.children, function (b) {
b.style.height = c.style.height;
});
});
JS小提琴演示 。
参考文献:
children()
。 each()
。 height()
。 $(function(){
$('.container').each(function(i,e){
$(this).find('.box').css('height',$(this).height())
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.