使用CSS过渡动画最大高度

时间:2013-04-16 04:37:17

标签: css3 css-transitions css-animations

我想创建一个仅由类名驱动的展开/折叠动画(javascript用于切换类名)。

我正在上课max-height: 4em; overflow: hidden;

和另一个max-height: 255em;(我也尝试过值none,它根本没有动画效果)

这是动画:transition: max-height 0.50s ease-in-out;

我使用CSS过渡在它们之间切换,但是浏览器似乎在动画所有额外的em,因此它会在崩溃效果中产生延迟。

有没有一种方法可以做到这一点(同样的精神 - 使用css类名)没有副作用(我可以设置较低的像素数,但这显然有缺点,因为它可能会切断合法文本 - 这就是具有重要价值的原因,因此它不会切断合法的长文本,只会删除可笑的长文本)

请参阅jsFiddle - http://jsfiddle.net/wCzHV/1/(单击文本容器)

6 个答案:

答案 0 :(得分:51)

修复延迟解决方案:

将cubic-bezier(0,1,0,1)转换函数放入元素。

SCSS

.text {
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.5s cubic-bezier(0, 1, 0, 1);

  &.full {
    max-height: 1000px;
    transition: max-height 1s ease-in-out;
  }
}

CSS

.text {
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.5s cubic-bezier(0, 1, 0, 1);
}

.text.full {
  max-height: 1000px;
  transition: max-height 1s ease-in-out;
}

答案 1 :(得分:8)

这是一个古老的问题,但我只想找到一种方法来做到这一点,并希望将其粘贴在某处,以便我知道在哪里可以找到它我应该再次需要它:o)

所以我需要一个带有可点击的“sectionHeading”div的手风琴,它显示/隐藏相应的“sectionContent”div。部分内容div具有可变高度,这会产生问题,因为您无法将高度设置为100%。我已经看到其他答案建议动画最大高度,但这意味着当您使用的最大高度大于实际高度时,有时会出现延迟。

这个想法是在加载时使用jQuery来查找并明确设置“sectionContent”div的高度。然后为每个点击处理程序添加一个css类'noHeight'来切换它:

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

为了完整性,相关的css类:

.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;
}

现在高度过渡没有任何延迟。

答案 2 :(得分:3)

如果有人正在阅读本文,我还没有找到解决方案并且只使用扩展效果(通过将transition样式移动到扩展类定义来实现)

答案 3 :(得分:1)

解决方案实际上非常简单。创建一个具有内容的子div。父div将是展开折叠的div。

在加载时,父div将具有最大高度。切换时,您可以编写document.querySelector('.expand-collapse-inner').clientHeight;来检查孩子的身高,并使用javascript设置maxheight。

在CSS中,您将拥有这个

.parent {
transition: max-height 250ms;
}

答案 4 :(得分:0)

使用 display:flex 。这将起作用:

.parent > div {
  display: flex;
  flex-direction: column;
  height: 0px;
  max-height: 0px;
  opacity: 0;
  overflow: hidden;
  transition: all 0.3s;
}

.parent > div.active {
  opacity: 1; 
  height: 100%;
  max-height: none; /* important for animation */
}

答案 5 :(得分:-2)

您可以使用jQuery Transit完成此操作:

$(function () {
    $(".paragraph").click(function () {
        var expanded = $(this).is(".expanded");
        if (expanded) 
        {
            $(this).transition({ 'max-height': '4em', overflow: 'hidden' }, 500, 'in', function () {$(this).removeClass("expanded"); });
        } 
        else 
        {
            $(this).transition({ 'max-height': $(this).get(0).scrollHeight, overflow: ''}, 500, 'out', function () { $(this).addClass("expanded"); });
        }
    });
});

你可以根据自己的喜好稍微整理一下,但这应该做你想要的。

JS Fiddle Demo