我正在寻找一种方法,我可以使我的所有div具有相同的高度。我尝试了以下内容:
HTML:
@foreach (var Image in Model)
{
<div class="col-sm-3 test2">
<div class="thumbnail">
<a class="img-responsive" href="~/Content/img/@Image.imgUrl" data-lightbox="roadtrip" data-title="My caption">
<img class="img-responsive" id="ImageThumb" src="~/Content/img/@Image.imgUrl">
</a>
<div class="caption">
<h3>@Image.Title</h3>
<p>@Image.imgDesc</p>
</div>
</div>
</div>
}
Jquery的:
$(document).ready(function () {
$('.test2').each(function () {
var highestBox = 0;
$(this).find('.thumbnail').each(function () {
if ($(this).height() > highestBox) {
highestBox = $(this).height();
}
})
$(this).find('.thumbnail').height(highestBox);
});
});
但这不起作用?我做错了什么?
答案 0 :(得分:1)
var hghtArr = [];
$(".test2 .thumbnail").each(function() {
hghtArr.push($(this).height());
});
var getMaxHgt = Math.max.apply(Math,hghtArr);
$(".test2 .thumbnail").height(getMaxHgt);
希望这可能有所帮助,逻辑很简单。
收集阵列下的所有高度,找到最大高度,并应用于所有。
答案 1 :(得分:-2)
这里不需要javascript,你可以使用display:flex(参见:https://css-tricks.com/snippets/css/a-guide-to-flexbox/)。
更新: 凯西注意后,这是代码:
HTML:
<div class="foo">
<div class="col-sm-3 test2" style="background:yellow;">
<div class="thumbnail">
<a class="img-responsive" href="~/Content/img/@Image.imgUrl" data-lightbox="roadtrip" data-title="My caption">
<img class="img-responsive" id="ImageThumb" src="~/Content/img/@Image.imgUrl">
</a>
<div class="caption">
<h3><br>FOO BAW<br></h3>
<p><br><br></p>
</div>
</div>
</div>
<div class="col-sm-3 test2" style="background:red;">
<div class="thumbnail">
<a class="img-responsive" href="~/Content/img/@Image.imgUrl" data-lightbox="roadtrip" data-title="My caption">
<img class="img-responsive" id="ImageThumb" src="~/Content/img/@Image.imgUrl">
</a>
<div class="caption">
<h3>FOO BAW</h3>
<p>FOO BAW</p>
</div>
</div>
</div>
</div>
CSS:
.foo {
display:flex;
flex-direction: row;
}
兼容性: CSS 3
小提琴: https://jsfiddle.net/BenoitNgo/nc20f35z/6/
结论:
我们的想法是在父级上使用flex容器。