当前位置:网站首页>设置 height: auto 却无法触发 transition 动画的解决方案
设置 height: auto 却无法触发 transition 动画的解决方案
2022-08-02 07:31:00 【Pandy : )】
当 height: auto 时,设置 transition 是无法触发动画的,CSS 需要知道具体的 height 值,因此引申其他解决方案:
- 方案一:使用
transform的scaleY,去放大缩小。- 缺点
- 内容会变形
- 会占据原来的内容尺寸
- 缺点
- 方案二:设置
max-height- 缺点
- 随着内容的增加,需要重新考虑设置
max-height的值 transition-timing是作用在max-height上的
- 随着内容的增加,需要重新考虑设置
- 缺点
- 方案三:获取元素的
height,重新设置。- 缺点
- 非纯 CSS
- 缺点
可以看到,每种方案不优雅,矮个子里拔高。接下来来拔一下方案三,我们将以 React 为例子:
- 创建一个组件,使用按钮去展开收缩
<div className={styles.wrapper}>
<Button className={styles.button} onClick={
collapseChange}>
{isExpand ? "Collapse" : "Expand"}
</Button>
<div className={clsx(styles.content, isExpand && styles.expanded)} style={
{
height: height + "px", }}Ï >
<div ref={ref}>{children}</div>
</div>
</div>
- 创建
ref,引用元素,当用户点击展开按钮时,获取元素的高度height
const ref = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState<number>(0);
const [isExpand, setIsExpanded] = useState(defaultIsExpanded);
const collapseChange = () => {
if (isExpand) {
setHeight(0);
} else {
setHeight(ref.current?.clientHeight ?? 0);
}
setIsExpanded(!isExpand);
};
这里可以缓存元素的高度,但是这里业务场景中,子元素的高度可能会动态变化,因此不做缓存。
- 设置 CSS,当元素高度变化时,触发
transition动画
.content {
grid-column: span 2;
transition: height 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;
transition-duration: 242ms;
overflow-y: hidden;
}
我是 Pandy,一个喜欢英语的程序猿
关注公众号 Yopth,回复「加群」,加入「翻译互助群」,我们加入一起充电英语
REFERENCE
边栏推荐
猜你喜欢

MGRE环境下的OSPF

PLSQL Developer安装和配置

Aided by training and learning by battle | The new version of the Offensive and Defense World Platform is officially launched!

sql创建表格 如图 运行完提示invalid table name 是什么原因

FormData upload binary file, object, object array

暂未找到具体原因但解决了的bug

Buried development process

数据表格化打印输出

HCIP 第十一天

MySQL优化:从十几秒优化到三百毫秒
随机推荐
Splunk Filed Alias field name
OC-error prompt
Compact格式下MySQL的数据如何存储到磁盘
数据中台:始于阿里,兴于DaaS
Xilinx Constraint Study Notes - Timing Constraints
17、生成长图,并上传至服务器
JVM垃圾回收与性能调优方式
I.MX6U-ALPHA开发板(定时器按键消抖)
Ask a question, my Flinkcdc has run through, I can monitor the binlog of msql, and I can also send kafk
Neural network
Introduction to Totem Pole and Push-Pull Circuits
59: Chapter 5: Develop admin management services: 12: MongoDB usage scenarios; (non-core data, non-core data with a relatively large amount of data, small private files such as face photos;)
MySQL常见索引类型
MySQL事务隔离级别详解
【Unity3D】初学加密技巧(反破解)
MySQL-Execution Process + Cache + Storage Engine
Metasploit (MSF) Basic Super Detailed Edition
MySQL error 1055 solution: [Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains
uni.navigateBack 中的坑
Visual Analysis of DeadLock