【问题标题】:get height from the highest div and apply it to others从最高 div 获取高度并将其应用于其他人
【发布时间】:2011-12-30 12:40:08
【问题描述】:

基本上

我很少有 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 元素)

  • 应用外层高度 给他们所有人

但我找不到一个好的/漂亮的方法(有一个解决方案,但我需要很多 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 中,这是问题所在吗?

【问题讨论】:

  • 我想知道这段代码“('header:eq(0)')”。据我所知,您为 HTML 标记“
    ”添加了高度,不是吗?

标签: javascript jquery height


【解决方案1】:

游戏有点晚了,但你可以使用数组:

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】:

    不要添加显示无,而是给他们“隐藏”类并使用它。

    $(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));
    });
    

    【讨论】:

    • 或者跳过 if() 测试,直接使用:height = Math.max( height, $(this).outerHeight() )
    • 会很完美,但大多数容器都是隐藏的;编辑问题
    • 已编辑,因此它将显示隐藏的 div,获取它们的高度,然后隐藏它们(仅具有隐藏类的那些)。现在应该适合你了。
    • 使用outerHeight不能设置元素高度,使用height()或者css('height', value)
    【解决方案3】:

    试试这个:

    $(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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-24
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 2016-05-31
      相关资源
      最近更新 更多