我需要一个函数来获取 div 内最高元素的高度。
我有一个包含许多其他元素的元素(动态生成),当我使用 $(elem).height() 询问容器元素的高度时,我得到的高度比其中的某些内容要小。里面的一些元素是比这个元素所说的尺寸更大的图像。
我需要知道最高元素,这样我才能得到它的高度。
我需要一个函数来获取 div 内最高元素的高度。
我有一个包含许多其他元素的元素(动态生成),当我使用 $(elem).height() 询问容器元素的高度时,我得到的高度比其中的某些内容要小。里面的一些元素是比这个元素所说的尺寸更大的图像。
我需要知道最高元素,这样我才能得到它的高度。
我在http://css-tricks.com/snippets/jquery/equalize-heights-of-divs找到了这个看起来更直接和更短的片段
var maxHeight = 0;
$(yourelemselector).each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
});
$(yourelemselector).height(maxHeight);
你总是可以这样做:
var t=0; // the height of the highest element (after the function runs)
var t_elem; // the highest element (after the function runs)
$("*",elem).each(function () {
$this = $(this);
if ( $this.outerHeight() > t ) {
t_elem=this;
t=$this.outerHeight();
}
});
编辑使其再次工作。
如果 div 元素小于其子元素,则子元素可能是浮动的。你能让div像孩子一样大吗?
如果可以,请在底部添加一个清除元素以使 div 包装它的子元素:
<div id="someParent">
<p>test</p>
<img src="test1.png" alt="test1" style="float: left" />
<img src="test2.png" alt="test2" style="float: left" />
<div style="clear: both;"></div>
</div>
或者应用一个clearfix CSS 解决方案来做几乎相同的事情,但没有额外的标记或清除 div。
然后包含的 div 将获得与最高子元素相同的高度,您可以通过以下方式获得它:
$("#someParent").height();
就我而言,我必须将它与响应式设计一起使用,所以我让它与窗口大小调整一起使用。
function fixHeight(elem){
var maxHeight = 0;
$(elem).css('height','auto');
$(elem).each(function(){
if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$(elem).height(maxHeight);
}
$(window).resize(function () {
fixHeight('.myelement');
});
$(document).ready(function(e) {
fixHeight('.myelement');
});
我希望这会对某人有所帮助!
快乐的编码家伙!:)