当前位置:网站首页>设置 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
边栏推荐
- Mysql各个大版本之间的区别
- Metasploit(MSF)基础超级详细版
- Introduction to Totem Pole and Push-Pull Circuits
- 2022-08-01 第四小组 修身课 学习笔记(every day)
- 用户身份标识与账号体系实践
- Comprehensive experiment of MPLS and BGP
- 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 - based
- OC-error prompt
- PanGu-Coder:函数级的代码生成模型
猜你喜欢
随机推荐
MySQL优化之慢日志查询
Link with Game Glitch
Fatal error compiling: 无效的目标发行版: 11
WebForm DropDownList bind year and month respectively
MySQL-数据库事务详解
Understand the Chisel language. 30. Chisel advanced communication state machine (2) - FSMD: Take Popcount as an example
MySQL-底层设置
AcWing 2811. 最长公共子串(后缀自动机 fa 指针的性质)
Ask a question, my Flinkcdc has run through, I can monitor the binlog of msql, and I can also send kafk
7.联合索引(最左前缀原则)
spark read folder data
Chain Of Responsibility
理论问题与工程问题的差异在哪里?
apt & apt-get commands
WebRTC系列-SDP之编码信息收集
MySQL之创建表的基本操作
(2022 Nioke Duo School 5) C-Bit Transmission (Thinking)
Data Middle Office: Started in Ali, Prosperous in DaaS
如何保护智能家居不受黑客攻击
ROS file system and related commands