【问题标题】:CSS height animation on element with dynamic height [duplicate]具有动态高度的元素上的CSS高度动画[重复]
【发布时间】:2017-10-21 05:58:44
【问题描述】:

我有一个动态高度的 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 具有最小高度,因此缩小动画有效。

有没有办法在纯 CSS 中解决这个问题?

【问题讨论】:

  • 将 height:200px 改为 max-height:200px;

标签: css css-animations


【解决方案1】:

删除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: 200px;
  overflow: auto;
}

.max {
  transition: all .3s ease-in-out;
  min-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;
}
<div class="text" contentEditable="true"></div>
<button id="button">Click</button>

【讨论】:

  • 我看不出这是动态的。它仍然是 .max 中 200 的固定高度
【解决方案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/

这会产生预期的效果吗?

【讨论】:

  • 不,现在你又有了一个 200px 的固定高度。
猜你喜欢
  • 2017-03-13
  • 2023-01-10
  • 2017-08-30
  • 2012-05-23
  • 2012-12-13
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 2016-07-11
相关资源
最近更新 更多