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

CSS悬停触发动画时切换div文本 解决原文本残留问题

问题原因

你当前代码的核心问题是:默认文本放在.content的::before伪元素上,悬停时仅为::after伪元素添加了新文本的动画逻辑,两个伪元素是独立渲染的,你没有对悬停状态下的::before做任何隐藏/清空处理,所以原始文本会一直留在页面上和新文本同时显示。

修复后可直接运行的代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Animation</title>
    <style>
        .container{
            height:500px;
            width:500px;
            background-color: red;
        }
        .child{
            display: flex;
            justify-content: center;
            align-items: center;
            height:50%;
            width:50%;
            background-color: blue;
        }
        .container:hover .child{
            animation: the-animation 1s ease-in forwards;
        }
        .content{
            position: relative;
        }
        /* 默认显示的原始文本 */
        .content::before{
            content:"The text Before";
            position: absolute;
            inset: 0;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        /* 悬停时隐藏原始文本,时序和切换动画同步 */
        .container:hover .content::before{
            animation: hide-origin 1s ease-in forwards;
        }
        /* 切换后的新文本容器 */
        .content::after{
            content:"";
            position: absolute;
            inset: 0;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .container:hover .content::after{
            animation: change-text 1s ease-in forwards;
        }

        @keyframes hide-origin{
            99% {
                content: "The text Before";
                opacity: 1;
            }
            100% {
                content: "";
                opacity: 0;
            }
        }

        @keyframes change-text{
            99%{
                content: "This is the text";
            }
            100%{
                content:"IT WORKS"
            }
        }
        
        @keyframes the-animation{
            0%{
                height:250px;
                width:250px;
            }
            100%{
                height:500px;
                width:500px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="child">
            <span class="content"></span>
        </div>
    </div>
</body>
</html>
关键调整说明
  • 给.content设置相对定位,让::before和::after两个伪元素通过绝对定位完全重叠,避免文本切换时出现位置偏移
  • 新增原始文本的隐藏动画,在1s动画周期的最后一帧清空::before的内容,和新文本的显示时序完全对齐,不会出现两个文本同时显示的问题
  • 移除了.child上多余的transform过渡属性,避免和尺寸变化动画产生冲突
  • 给两个伪元素统一设置居中规则,保证文本始终在蓝色块的正中心显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:27:46