Animating max-height with CSS transitions

前端 未结 6 2048
死守一世寂寞
死守一世寂寞 2020-12-02 21:58

I want to create an expand/collapse animation that\'s powered only by classnames (javascript is used to toggle the classnames).

I\'m giving one class max-heigh

6条回答
  •  半阙折子戏
    2020-12-02 22:31

    This is an old question but I just worked out a way to do it and wanted to stick it somewhere so I know where to find it should I need it again :o)

    So I needed an accordion with clickable "sectionHeading" divs that reveal/hide corresponding "sectionContent" divs. The section content divs have variable heights, which creates a problem as you can't animate height to 100%. I've seen other answers suggesting animating max-height instead but this means sometimes you get delays when the max-height you use is larger than the actual height.

    The idea is to use jQuery on load to find and explicitly set the heights of the "sectionContent" divs. Then add a css class 'noHeight' to each a click handler to toggle it:

    $(document).ready(function() {
        $('.sectionContent').each(function() {
            var h = $(this).height();
            $(this).height(h).addClass('noHeight');
        });
        $('.sectionHeader').click(function() {
            $(this).next('.sectionContent').toggleClass('noHeight');
        });
    });
    

    For completeness, the relevant css classes:

    .sectionContent {
        overflow: hidden;
        -webkit-transition: all 0.3s ease-in;
        -moz-transition: all 0.3s ease-in;
        -o-transition: all 0.3s ease-in;
        transition: all 0.3s ease-in;
    }
    .noHeight {
            height: 0px !important;
    }
    

    Now the height transitions work without any delays.

提交回复
热议问题