2011-08-18 75 views
1

我有8個選項卡在所有不同的高度範圍內。每個類都有相似的類,並且活動選項卡具有它自己的類。jQuery添加高度父母

如何獲取活動選項卡的高度並將其作爲樣式添加到其父項中? (當不同的選項卡變爲活動狀態時,需要添加新的高度。)

下面的代碼是我試圖獲取的一個示例。謝謝。

<div id="parent" style="height: 1426px;"> 
    <div class="child"></div>   (height: 2245px) 
    <div class="child"></div>   (height: 983px) 
    <div class="child"></div>   (height: 3004px) 
    <div class="child active"></div> (height: 1426px) 
    <div class="child"></div>   (height: 1209px) 
</div> 

回答

2

你可以這樣說:

$('#parent').height($('.active').height()); 

然而,由於孩子的父母下,你應該請改爲:

$('#parent').height($('.active').outerHeight()); 

如果您希望在選擇新選項卡時設置高度,則必須將該線放在設置「活動」類的相同位置。它可能是這個樣子:

$('#parent').find('.child').click(function() { 
    var $this = $(this); 
    $this.addClass('active').siblings().removeClass('active'); 
    $('#parent').height($this.outerHeight()); 
}); 
2
var childHeight = $(".active", "#parent").height(); 
$("#parent").height(childHeight) 

或一個班輪

$("#parent").height($(".active", "#parent").height()); 
+0

謝謝,這幾乎是我所需要的。如果選擇不同的選項卡,父級div如何獲得新的高度? – cnotethegr8

+0

如果「tab」是其中一個子div,那麼你可以在dom元素上單擊鼠標並根據給定的代碼設置高度 – cpjolicoeur

0

這樣:

var child_selected_height = $('div.child.active').css('height'); 
$('#parent').css('height', child_selected_height); 

或更爲簡單:

$('#parent').css('height', $('div.child.active').css('height'));