具有动态高度的元素的CSS高度动画

13

我有一个高度动态变化的 div,我想在高度增加时使用动画效果。问题是我无法设置 div 的高度(它必须是动态的),因此没有什么可以进行动画处理。

.text {
  transition: all .3s ease-in-out;
  min-height: 20px;
  max-height: 200px;
  overflow: auto;
}

.max {
  transition: all .3s ease-in-out;
  height: 200px;
  min-height: 200px;
}

https://jsfiddle.net/abk7yu34/5/

需要注意的是,收缩动画之所以有效,是因为 div 元素设置了 min-height。

是否有一种纯 CSS 的方法来解决这个问题?


将“height:200px”更改为“max-height:200px;”。 - Chiller
2个回答

8

移除 height: 200px;,这样你就可以实现展开和折叠的动画效果。

此外,使用以下代码在新行上添加动画效果:

@keyframes lineInserted {
  from {
    height: 0;
  }
  to {
    height: 20px; /* your line height here */
  }
}
div[contenteditable] > div {
  animation-duration: 0.3s;
  animation-name: lineInserted;
  transition: height 0.3s;
}

document.querySelector('#button').addEventListener('click', function() {
  document.querySelector('.text').classList.toggle('max');
});
.text {
  background: green;
  color: #fff;
  transition: all .3s ease-in-out;
  min-height: 20px;
  max-height: 90vh;
  overflow: auto;
}

.max {
  transition: all .3s ease-in-out;
  min-height:90vh;
}

@keyframes lineInserted {
  from {
    height: 0;
  }
  to {
    height: 20px; /* your line height here */
  }
}
div[contenteditable] > div {
  animation-duration: 0.3s;
  animation-name: lineInserted;
  transition: height 0.3s;
}
<div class="text" contentEditable="true"></div>
<button id="button">Click</button>


18
我不认为这是动态的。它仍然是一个最大高度为200像素的固定高度。 - geoidesic
3
@geoidesic 这是一个非常旧的帖子,但我认为原帖作者想要一个可切换高度的功能,当你点击时它会展开,再次点击它就会折叠。 - Dalin Huang
更新为使用90vh,您也可以放置任何您想要的内容。 - Dalin Huang

2
尝试移除文本类的max-height属性,转而过渡到一个新的(动态的)最小高度。
.text {
    background: green;
    color: #fff;
    transition: min-height .3s ease-in-out;
    min-height: 20px;
    overflow: auto;
}

.max {
    transition: min-height .3s ease-in-out;
    min-height: 200px;
}

https://jsfiddle.net/Alessi42/abk7yu34/8/

这是否产生了预期的效果?

15
不,现在你又有了一个固定的高度,为200像素。 - Juuro

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