Animate height change on Bootstrap's Carousel

2019-04-08 07:12发布

问题:

I'm attempting to use Bootstrap's Carousel to handle content that isn't the same height. The heights will differ based on the browsers width, and there is content below the carousel. I'd like to use CSS to animate the height change between slides. With some help from a friend I almost have this working in FireFox (the first slide jumps, the rest animate) but an obvious bug is happening with the sliding animation in Chrome.

Any input would be great, even if you think I should handle the height animation in a completely different way, please let me know!

Here is the JS and CSS that I think matter, but the whole thing is on JS Fiddle: http://jsfiddle.net/tkDCr/

JS

$('#myCarousel').carousel({
    interval: false
});

$('#myCarousel').bind('slid', function(e) {
    console.log('slid',e);
});

$('#myCarousel').bind('slide', function(e) {
    console.log('slide',e);
    var next_h = $(e.relatedTarget).outerHeight();
    console.log(next_h);
    $('.carousel').css('height', next_h);
});

By commenting out lines 12 and 13 of the JavaScript you can see that the bug is clearly being caused by assigning the variable next_h with the data from '$(e.relatedTarget).outerHeight();'. Even if the variable isn't used it still breaks the animation. Commenting out 11,12, and 13, will show you how the carousel functions normally.

CSS

.carousel {
    width: 80%;
    margin-left: auto;
    margin-right: auto;
    background: lightgoldenrodyellow;
    -webkit-transition: height .5s ease;
    -moz-transition: height .5s ease;
    -ms-transition: height .5s ease;
    -o-transition: height .5s ease;
    transition: height .5s ease;
}

Thank you in advance.

回答1:

You can get around the problem by delaying the call to outerHeight() by a short timeout:

$('#myCarousel').bind('slide', function(e) {
    setTimeout(function () {
        var next_h = $(e.relatedTarget).outerHeight();
        $('.carousel').css('height', next_h);
    }, 10);
});

Also, you probably want to set the height of .carousel to something in the css, otherwise the first transition will begin at height 0, making it drop from the top.

I updated your fiddle here: http://jsfiddle.net/tkDCr/3/



回答2:

// animate do the same - timeout is not needed

 $('#myCarousel').carousel();
 $('#myCarousel').bind('slide', function(e) {
       $('#myCarousel').animate({height: $(e.relatedTarget).outerHeight()});
 });         

// After using animate, there is no need for transition in css (or height)