当前位置:网站首页>设置 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
边栏推荐
- ROS文件系统以及相关命令
- 五款优秀免费的在线抠图工具
- RIP综合实验
- OC-NSDictionary
- WebForm DropDownList bind year and month respectively
- OSPF 综合实验
- Aided by training and learning by battle | The new version of the Offensive and Defense World Platform is officially launched!
- Azure Synapse Analytics上创建用户并赋予权限
- Conditional constructor ~wapper
- flutter 参数传一个范型数据
猜你喜欢

MySQL - locking mechanism

HCIP第二天

Enterprise training and reproduction guidebook - training and reasoning of the OpenPose model based on Huawei ModelArts platform, realizing the recognition of two behaviors of climbing and climbing ov

7.联合索引(最左前缀原则)

停止精神内耗 每日分享

Splunk Field Caculated Calculated Field

MySQL - based

牛客2022 暑期多校4 D Jobs (Easy Version)(递推优化策略)

设置工作模式与环境(中):建造二级引导器

Introduction to mysql operation (4) ----- data sorting (ascending, descending, multi-field sorting)
随机推荐
MySQL压缩包方式安装,傻瓜式教学
基于PyTorch的flappy bird游戏
典型的一次IO的两个阶段是什么?阻塞、非阻塞、同步、异步
flutter在导航栏处实现对两个列表的点击事件
研发过程中的文档管理与工具
Link with Game Glitch
postgres groupby merge strings
停止精神内耗 每日分享
Modify apt-get source to domestic mirror source
Understand the Chisel language. 30. Chisel advanced communication state machine (2) - FSMD: Take Popcount as an example
OC-NSString
MySQL-基础
LeetCode brush questions (7)
Metasploit (MSF) Basic Super Detailed Edition
redis-高级篇
HCIP 第四天
Mysql各个大版本之间的区别
Transimpedance amplifier
五款优秀免费的在线抠图工具
WebRTC系列-SDP之编码信息收集