
解决 css 过渡动画问题
问题描述:
在一个包含
标签和 .box 元素的 HTML 结构中,当
标签显示时,.box 元素的高度会突然变化,无法满足 transition all .5s 设置的过渡动画效果。用户希望为 .box 元素的高度变化添加平滑的过渡动画。
解决方法:
CSS 动画不支持 height: auto。要实现平滑的高度变化,可以使用以下解决方案:
- 使用 JavaScript 获取 .box 元素的实际高度。
- 单击按钮或触发某个事件时,切换高度。
示例代码:
CSS:
.box {
background-color: blue;
overflow: hidden;
transition: all 1s;
}JS:
const autoH = $('.box').height();
let h = 0;
$('.box').height(0);
$('.button').click(function() {
$('.box').height(h ^= autoH);
});










