在Bootstrap的Carousel(v2.3.2)上如何实现高度变化动画

6
我正在尝试使用Bootstrap的Carousel来处理高度不同的内容。高度将根据浏览器宽度而异,并且轮播下方有内容。我想使用CSS来在幻灯片之间动画变化高度。在朋友的帮助下,我几乎在FireFox中实现了这个功能(第一张幻灯片会跳动,其余的都是动画),但在Chrome中滑动动画明显存在错误。
任何建议都很好,即使您认为我应该以完全不同的方式处理高度动画,请告诉我!
以下是我认为重要的JS和CSS,但整个内容都在JS Fiddle上:http://jsfiddle.net/tkDCr/
$('#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);
});

通过注释掉 JavaScript 的第 12 和第 13 行,可以看到该 bug 明显是由将变量"next_h" 赋值为 '$(e.relatedTarget).outerHeight();' 的数据引起的。即使不使用该变量也会破坏动画效果。注释掉 11、12 和 13 行,就可以看到轮播图的正常功能。
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.

2个回答

10
// 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)

9

您可以通过延迟对outerHeight()的调用来解决问题:

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

此外,您可能想在CSS中设置.carousel的高度,否则第一个转换将从高度0开始,使其从顶部下降。
我在这里更新了您的fiddle:http://jsfiddle.net/tkDCr/3/

谢谢。这个很好用。很抱歉我没有足够的声望来为您点赞! - brant
自从Bootstrap 3.0以来,应该使用'slide.bs.carousel'事件。 - Vitaliy Kotov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接