You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用CSS的interpolate-size属性实现height:auto的自动动画?

问题解答

你的现有写法不可行,原因很直接:

  • CSS transition 本身无法对 height: auto 做平滑过渡,因为浏览器没法计算"auto"到"auto"之间的插值变化;
  • 你用到的 interpolate-size: allow-keywords 是实验性属性,仅极少数浏览器支持,完全没法作为通用方案。

下面给你两种实用的实现方式:

方式一:用max-height模拟动画

这种写法最简单,适合大部分场景:

<button id="append">append</button>
<div id="text">test</div>
#text {
  max-height: 20px; /* 对应初始文本的高度 */
  width: 200px;
  border: 1px solid green;
  transition: max-height 1s ease;
  overflow: hidden; /* 避免内容提前溢出 */
}
document.getElementById("append").addEventListener('click', () => {
  const textEl = document.getElementById("text");
  textEl.innerHTML += ' test test test test test test';
  // 把max-height设为元素实际滚动高度,触发动画
  textEl.style.maxHeight = textEl.scrollHeight + 'px';
});

注意:max-height要设得比你可能出现的最大内容高度大,不然内容会被截断。

方式二:JS计算高度实现精确动画

如果需要完全精准的高度过渡,就用这种方式手动计算前后高度:

<button id="append">append</button>
<div id="text">test</div>
#text {
  width: 200px;
  border: 1px solid green;
  transition: height 1s ease;
  overflow: hidden;
}
document.getElementById("append").addEventListener('click', () => {
  const textEl = document.getElementById("text");
  // 记录当前高度
  const oldHeight = textEl.offsetHeight;
  // 先关掉过渡,避免添加文本时的突兀变化
  textEl.style.transition = 'none';
  // 添加新文本
  textEl.innerHTML += ' test test test test test test';
  // 获取新高度
  const newHeight = textEl.offsetHeight;
  // 把元素高度设回旧值,准备动画
  textEl.style.height = oldHeight + 'px';
  // 强制浏览器重绘,确保它能捕捉到初始状态
  void textEl.offsetWidth;
  // 恢复过渡,触发动画到新高度
  textEl.style.transition = 'height 1s ease';
  textEl.style.height = newHeight + 'px';
});

内容的提问来源于stack exchange,提问作者ais

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:33:21