从最高的div获得高度并将其应用于其他人

时间:2011-11-16 15:05:27

标签: javascript jquery height

基本上

我有几个具有灵活高度和固定填充的div,因此很难将它们全部放在同一高度,

我这样想:

$(document).ready(function(){
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content').outerHeight( $('header:eq(0)').outerHeight() );


    console.log($('header:eq(0)').outerHeight(true));
});

但问题是标题不是总是最高的,所以我需要

  • 检查哪一个更高(考虑到有多个.content元素)

  • 申请outerHeight 对所有人

但是我找不到一个好的/美丽的方式(有一个解决方案,但我需要很多if和变量)来做到这一点

任何线索?

- 编辑 -

在等待的时候我想出了这个

$(document).ready(function(){

    var height = 0;
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content,header').each(function(){
         if($(this).outerHeight() > height){
            height = $(this).outerHeight();
         }
    });
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content,header').each(function(){

             $(this).outerHeight(height);

    });

    console.log('highest height is '+height); //it doesn't output the highest value
});

但是大多数这些div都在display:none是问题吗?

3 个答案:

答案 0 :(得分:6)

不要添加display none,而是给它们“hide”类并使用它。

$(function(){
    var height = 0;
    $('.hide').show();
    $('header').each(function(){
        height = Math.max( height, $(this).outerHeight() )
    });
    $('.hide').hide();
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content').outerHeight(height);
    console.log($('header:eq(0)').outerHeight(true));
});

答案 1 :(得分:4)

比赛迟到,但你可以使用一个阵列:

var arr = $.makeArray()
$('div').each(function(){
    arr.push($(this).outerHeight());
});
$('div').css('height', Math.max.apply( Math, arr ));
console.log('highest height is '+Math.max.apply( Math, arr ));

查看我的示例 - http://jsfiddle.net/ZhG2S/

答案 2 :(得分:0)

试试这个:

$(document).ready(function(){
    var headerHeight = getTallestHeaderHeight()
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content').outerHeight(headerHeight);

    console.log(headerHeight);
});

function getTallestHeaderHeight() {
    var maxHeight = 0;
    $("HEADER").each(function() {
        if ($(this).outerHeight() > maxHeight)
            maxHeight = $(this).outerHeight()
    })

    return maxHeight;
}