You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现绝对定位元素空间的平滑过渡填充

问题:实现列表元素移除时后续元素平滑填充空间的过渡效果

我正在尝试实现列表元素添加或移除时的平滑过渡效果,核心需求是让后续元素能平滑过渡填充绝对定位元素状态改变后腾出的空间。我给列表中的后续元素应用了fade-move类(即transition all ease规则),想要复刻Vue官方的列表过渡示例效果,但目前测试案例中,当元素1被设置为绝对定位时,元素2会直接跳上去填充空间,而非平滑上滑。

测试代码(Test.tsx)

import classNames from 'classnames';
import React, { useEffect, useState } from 'react';

const Test: React.FC = () => {
    const [show, setShow] = useState(true);
    const [currentClass, setCurrentClass] = useState('');

    const toggleShow = () => {
        setShow(prevShow => !prevShow);
    };

    useEffect(() => {
        if (show) {
            setCurrentClass('fade-enter-from');
            requestAnimationFrame(() => {
                setCurrentClass('fade-enter-active fade-enter-to');
            });
        } else {
            setCurrentClass('fade-leave-from');
            requestAnimationFrame(() => {
                setCurrentClass('fade-leave-active fade-leave-to');
            });
        }
    }, [show]);

    return (
        <div className="container">
            <button onClick={toggleShow} className="mb-4 bg-blue-500 p-2 text-white">
                Toggle Element
            </button>
            <div className="relative">
                <div className={classNames('item', currentClass)}>
                    Element 1
                </div>

                <div className="item fade-move">Element 2</div>
            </div>
        </div>
    );
};

export default Test;

样式代码(app.css)

.container {
    position: relative;
    padding: 0;
    list-style-type: none;
}

.item {
    width: 100%;
    height: 60px;
    background-color: #f3f3f3;
    border: 1px solid #666;
    box-sizing: border-box;
    transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1); /* Apply transition to all items by default */
}

.fade-move,
.fade-enter-active,
.fade-leave-active {
    transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

/* 定义进入初始状态和离开结束状态 */
.fade-enter-from,
.fade-leave-to {
    opacity: 0;
    transform: scaleY(0.01) translate(30px, 0);
}

/* 确保离开元素脱离文档流,让移动动画计算正确 */
.fade-leave-active {
    position: absolute;
}

内容的提问来源于stack exchange,提问作者Orbitall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:34:59