开发者

jQuery add Height to parent

开发者 https://www.devze.com 2023-03-28 22:00 出处:网络
I have 8 tabs ranging in all different heights. Each having a similar class, and the active tab having its own class.

I have 8 tabs ranging in all different heights. Each having a similar class, and the active tab having its own class.

How can i get the height of the active tab and add it as a style to its parent? (When a different tab becomes active, the new height needs to be added.)

The code below is an example of what im trying to get. Thanks.

<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"&开发者_如何学Pythongt;</div>  ( height: 1426px )
  <div class="child"></div>         ( height: 1209px )
</div>


You can do it like this:

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

However, since the child is under the parent, you should probably do this instead:

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

If you want to set the height when a new tab is selected, you have to put that line at the same place where you set the "active" class. It could look something like this:

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


var childHeight = $(".active", "#parent").height();
$("#parent").height(childHeight)

or in a one-liner

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


This way:

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

or more simple:

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

精彩评论

暂无评论...
验证码 换一张
取 消