开发者

Expand/Collapse set height divs with same class using jQuery [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

jQuery div content partial hide, show all

I know this has been done and I have seen in peoples websites but I can't find it. So I am here.

I need to set up or list multiple divs (4 or 5) on a page with the same class and set each div about 50 pixels tall. I need them to expand to the div to the full height of the content. Assuming using show/hide or slideUp/slid开发者_StackOverfloweDown. And when the collapse happens, collapse the div back down to the 50 pixels. Again I want multiple divs with the same class and fire independently from each other.

Anybody seen this before. I saw this solution but was not quite what I need. I need an expand and close, as well as, all divs need to start out the same height then once the expand is clicked, that specific div needs to expand. Each can be open independent of each other.

Any ideas?


If you've got HTML structured like this:

<div class='expandable'>
    <p>Some content</p>
</div>
<div class='expandable'>
    <p>Some more content</p>
</div>

You can make that work with a bit of joint jQuery and CSS.

First, this CSS would force each .expandable to have a minimum height of 50px:

.expandable { min-height:50px; }

Then to take care of the expanding/collapsing, you can do something like:

jQuery(function($) {

    $('.expandable').bind('click', function () {
        $(this).children().toggle();
    });

});

This would hide/show the .expandable DIV's content everytime it is clicked. When the content is hidden, the CSS above would prevent the DIV from collapsing on itself smaller than 50px.

This would allow your .expandable to "expand" to it's content's true height when the content is shown as well. Take note that the content has to be in HTML DOM elements for this to work (predictably).

<!-- This should work -->
<div class='expandable'>
    <p>foo</p>
</div>

<!-- This probably won't -->
<div class='expandable'>
    bar
</div>


css class:

.toggledivs {height:50px;}
.max {height:150px;}

Then toggle the classes

$('.toggledivs').click(function(){
  $(this).toggleClass('max');
});

In that case they are all independent of each other. The initial HTML should be set up like

<div class="toggledivs">foo</div><div class="toggledivs">foo</div>

If you want to have like the first container (or any of em) add class 'max' to the element lika:

<div class="toggledivs max">foo</div><div class="toggledivs">foo</div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜