2010-09-03 152 views
0

我有2个divs,一个在另一个里面。如何比较嵌套div的高度?

<div id="ads_content" class="ads_contents"> 
    <div id="ads_text" class="ads_text"> 
     ... text contents ... 
    </div> 
</div> 

ads_content div的最大高度为230px,它有overflow:hidden。所以会显示来自ads_text div的明确数量的文本。我需要比较他们的高度,决定是否需要添加“展开”按钮。

我这样做:

$(document).ready(function() { 
    $('.ads_contents').each(function() { 
     var t = $(this); 
     var needed_height = t.children('.ads_text').css('height'); 
     var actual_height = t.css('height'); 
     if (actual_height < needed_height) { 
      t.after('<div class="expander" onclick="expand_collapse(' + getAdId(t.attr('id')) + ', this);">Mehr</div>'); 
     } 
    }); 
}); 

在Opera和FF一切都很好。 问题是: 在IE中,actual_height和needed_height是'auto'。在webkit中,它们的值是相等的,直到整个文档加载。

对于Chrome我已经做了一个解决方法,setTimeout为300毫秒,但这不是我想要的。任何人都可以告诉我,如何比较webkit和IE中这些div的高度?

回答

0
$(document).ready(function() { 
$('.ads_contents').each(function() { 
    var t = $(this); 
    var needed_height = t.children('.ads_text').height(); 
    var actual_height = t.height(); 
    if (actual_height < needed_height) { 
     t.after('<div class="expander" onclick="expand_collapse(' + getAdId(t.attr('id')) + ', this);">Mehr</div>'); 
    } 
}); 

});

0

有一种方法适用于所有浏览器,并且不需要jquery。 使用元素的clientHeight属性。

if (document.getElementById("YourelementId").clientHeight > '500') 
{ 
**do something** 
} 
else 
{ 
**do something else** 
} 
+0

只要将它与某个数字进行比较,就像我在上面的代码中显示的那样。 – Abhidemon 2015-04-27 07:31:08