当 height: auto
时,设置 transition
是无法触发动画的,CSS 需要知道具体的 height 值,因此引申其他解决方案:
transform
的 scaleY
,去放大缩小。
max-height
max-height
的值transition-timing
是作用在 max-height
上的height
,重新设置。
可以看到,每种方案不优雅,矮个子里拔高。接下来来拔一下方案三,我们将以 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);
};
这里可以缓存元素的高度,但是这里业务场景中,子元素的高度可能会动态变化,因此不做缓存。
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,回复「加群」,加入「翻译互助群」,我们加入一起充电英语 🔌