在隐藏/显示div上调整列高度

时间:2013-06-19 08:38:57

标签: jquery

我有一个包含两列的html页面。

<div class="span2 sameht">
    <div class="content">
        <div class="hidelevel">something</div>
        <div class="hidelevel">something</div>
        <div>something</div>
        <div>something</div>
    </div>
</div>

<div class="span3 sameht">
    <div class="content">
        <div>something</div>
        <div>something</div>
    </div>
</div>

对于我使用此代码的列具有相同的高度

$( function() {
    var maxHeight = 0
    $('.sameht').each(function() {
        if ($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
});
$('.sameht').height(maxHeight);
});

现在,当我以这种方式隐藏div(.hidelevel类)时,列高度不会动态调整大小。

$(function() {
    $(".hidelevel").hide();
})

每次隐藏/显示<div>时,是否可以重新调整列的高度?

由于

4 个答案:

答案 0 :(得分:0)

尝试使用隐藏功能:

    $(function () {

        $(".hidelevel").hide();
//after hide div. 1) set height to auto and 2) resize both div 
        var maxHeight = 0
//1) set height to auto 
        $('.sameht').css({ 'height': 'auto' });
//2) resize both div 
        $('.sameht').each(function () {
            if ($(this).height() > maxHeight) {
                maxHeight = $(this).height();
            }
        });
        $('.sameht').height(maxHeight);

    })

答案 1 :(得分:0)

$("#hidelevel").hide(); will not work. Because these is no element having hidelevel id.

使用这个:

$(".hidelevel").hide();

答案 2 :(得分:0)

捕获在函数中切换高度的代码。然后在隐藏元素时调用此函数。

<强>的Javascript

$( function() {
   adjustHeight();
    $("#toggle").click(function(){
        $(".hidelevel").toggle();
        adjustHeight();
    });
});


function adjustHeight(){
var maxHeight = 0
$('.sameht').each(function() {
    if ($(this).height() > maxHeight) {
    maxHeight = $(this).height();
    }
});
$('.sameht').height(maxHeight);
}

<强> HTML

<div class="span2 sameht">

    <div class="content">

        <div class="hidelevel">something</div>
        <div class="hidelevel">something</div>
        <div>something</div>
        <div>something</div>

    </div>

</div>

<div class="span3 sameht">

    <div class="content">

        <div>something</div>
        <div>something</div>

    </div>

</div>

<div id="toggle">Toogle Visibility</div>

工作示例 http://jsfiddle.net/jXgLd/

答案 3 :(得分:0)

您需要将高度调节器变成一个功能,以便您可以随时运行它:

function fixHeight() {
    var maxHeight = Math.max.apply(this, $('.sameht').map(function() { return $(this).height(); }));
    $('.sameht').height(maxHeight);
});

.hide接受回调。只要确保在隐藏元素时调用它(或者,只要确保在高度因任何原因而改变时调用它):

$(function() {
    $('#hidelevel').hide(fixHeight);
});
相关问题