jQuery - 设置 div 的最小高度

23

对于大多数人来说,这可能非常容易。但是我需要一个小片段,它查找div的当前高度(div的高度基于其中的内容而动态变化),然后将该值设置为css类的min-height值。

基本上这意味着我希望这个容器的最小高度与其当前高度完全相同。这可能是一个快速解决的问题 :)

3个回答

69

如果我理解你的意思正确,你可以按照以下步骤操作:

$(".foo").css("min-height", function(){ 
    return $(this).height();
});

是的,这个可以工作 :) 我问的原因是因为我有一个没有指定高度的div,在被其他内容填充之前就被清空了。使整个容器根据其中的内容动态调整大小。在没有内容和内容之间的这个小间隙中,div会收缩到其最小高度,然后再增长到所需的大小。这里的缺点是div不能动态地缩小,只能向上扩展。你知道绕过这个问题的好方法吗? - Kenny Bones

6

仅仅是一个概念的证明!

     // attend for dom ready
    $(function() {
        // hide .foo before we get it's height
        $('.foo').hide();
        // get the height, also the one mentioned below is a good one!
        var foo_height = $('.foo').height();
        // see if the actual height respect our needs! esample 180px
        if ( foo_height > 180 ) {
            // set the height and show it!
            //$('.foo').css('height', foo_height + 'px').show(); OR try
            $('.foo').height( foo_height ).show();
        } else {
            //do something else here
            }
});

这应该按预期工作!


1
var elt = document.getElementById("<%= this.your_element_id.ClientID %>");
elt.style.minHeight = elt.clientHeight + 'px';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接