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

已定义的CSS关键帧动画在hover状态下无法生效问题排查

问题:.glass元素hover时关键帧动画不生效

尝试给.glass类的hover状态添加关键帧动画,实现玻璃效果逐渐消失,但动画未正常生效。

原代码如下:

.glass{
    background: linear-gradient(
        90deg,
        transparent,
        transparent 0.75rem,
        var(--color-3) 2rem
    );
   
    height: 100%;
    width: 100%;
    backdrop-filter: blur(.65rem);
    filter: contrast(1.35);
    position: absolute;
    z-index: 99;
    inset: 0;
    opacity: 0.5;
    background-size: 2.5rem 100%;
    /* animation: mymove 5s infinite; */
}

@keyframes mymove {
    0%   {background-size: 2.5rem 100%;}
    25%  {background-size: 2.5rem 75%;}
    75%  {background-size: 2.5rem 25%;}
    100% {background-size: 2.5rem 0%;}
}


.glass:hover {
    animation: mymove 5s infinite;
    /* transition: 0.7;
    opacity: 1; */
}

预期效果:鼠标悬停时,已应用的玻璃效果逐渐消失。


问题分析

你当前的动画只修改了background-size的高度值,但玻璃效果的核心是backdrop-filter(模糊)、opacity(透明度)以及背景渐变的颜色,这些属性完全没在动画里变化。而且默认background-repeat: repeat,当background-size高度缩到0%后,背景会重复显示,反而达不到消失的效果。

修复方案

要实现玻璃效果逐渐消失,需要针对影响玻璃感的核心属性做动画,以下两种方式都可以实现需求:

方式1:用关键帧动画(适合复杂多阶段变化)

.glass{
    background: linear-gradient(
        90deg,
        transparent,
        transparent 0.75rem,
        var(--color-3) 2rem
    );
    height: 100%;
    width: 100%;
    backdrop-filter: blur(.65rem);
    filter: contrast(1.35);
    position: absolute;
    z-index: 99;
    inset: 0;
    opacity: 0.5;
    background-size: 2.5rem 100%;
}

@keyframes glassFadeOut {
    0% {
        backdrop-filter: blur(.65rem);
        opacity: 0.5;
        background: linear-gradient(
            90deg,
            transparent,
            transparent 0.75rem,
            var(--color-3) 2rem
        );
    }
    100% {
        backdrop-filter: blur(0);
        opacity: 0;
        background: linear-gradient(
            90deg,
            transparent,
            transparent 0.75rem,
            transparent 2rem
        );
    }
}

.glass:hover {
    /* 用forwards让动画结束后保持最后一帧状态,不需要循环就去掉infinite */
    animation: glassFadeOut 5s forwards;
}

方式2:用transition(适合简单状态切换,性能更好)

如果只是悬停消失、离开恢复的简单效果,用transition比关键帧动画更简洁:

.glass{
    background: linear-gradient(
        90deg,
        transparent,
        transparent 0.75rem,
        var(--color-3) 2rem
    );
    height: 100%;
    width: 100%;
    backdrop-filter: blur(.65rem);
    filter: contrast(1.35);
    position: absolute;
    z-index: 99;
    inset: 0;
    opacity: 0.5;
    background-size: 2.5rem 100%;
    /* 添加过渡动画,控制所有属性变化的时长和曲线 */
    transition: all 5s ease;
}

.glass:hover {
    backdrop-filter: blur(0);
    opacity: 0;
    background: linear-gradient(
        90deg,
        transparent,
        transparent 0.75rem,
        transparent 2rem
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:38:33