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

Blazor中CSS Keyframes动画fill重名导致对错对勾动画颜色一致如何解决

问题原因

CSS中同名的@keyframes规则会被后定义的内容覆盖,你先声明的绿色填充fill动画被后面红色的同名fill动画覆盖,才会出现两类动画填充色一致的问题。同时你目前代码中stroke、scale两类动画逻辑完全一致,重复定义属于冗余代码,可以直接复用。


方案1:快速修复(重命名动画)

只需要给不同颜色的填充动画单独命名,公共动画保留一份即可,修改核心代码如下:

/* 公共动画,逻辑完全一致无需重复定义 */
@keyframes stroke {
    100% {
        stroke-dashoffset: 0;
    }
}
@keyframes scale {
    0%, 100% {
        transform: none;
    }
    50% {
        transform: scale3d(1.1, 1.1, 1);
    }
}
/* 绿色专属填充动画 */
@keyframes fill-green {
    100% {
        box-shadow: inset 0px 0px 0px 30px #7ac142;
    }
}
/* 红色专属填充动画 */
@keyframes fill-red {
    100% {
        box-shadow: inset 0px 0px 0px 30px #ff0000;
    }
}

对应修改两个容器的动画引用:

  • 绿色对勾.checkmark的animation属性改为:animation: fill-green .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  • 红色叉号.checkmark_red的animation属性改为:animation: fill-red .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;

删除原代码中重复定义的stroke、scale、fill动画即可解决冲突。


方案2:代码优化(CSS变量实现样式复用)

因为两类动画除了颜色无任何逻辑差异,你可以用CSS变量统一抽离颜色参数,大幅减少冗余代码,后续扩展也更方便:

/* 公共基础样式 */
.checkmark {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    stroke-width: 2;
    stroke: #fff;
    stroke-miterlimit: 10;
    margin: 10% auto;
    box-shadow: inset 0px 0px 0px var(--color);
    animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
}
.checkmark__circle {
    stroke-dasharray: 166;
    stroke-dashoffset: 166;
    stroke-width: 2;
    stroke-miterlimit: 10;
    stroke: var(--color);
    fill: none;
    animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}
.checkmark__icon {
    transform-origin: 50% 50%;
    stroke-dasharray: 48;
    stroke-dashoffset: 48;
    animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}
/* 颜色变量定义 */
.checkmark.success {
    --color: #7ac142;
}
.checkmark.error {
    --color: #ff0000;
}
/* 公共动画 仅需定义一次 */
@keyframes stroke {
    100% {
        stroke-dashoffset: 0;
    }
}
@keyframes scale {
    0%, 100% {
        transform: none;
    }
    50% {
        transform: scale3d(1.1, 1.1, 1);
    }
}
@keyframes fill {
    100% {
        box-shadow: inset 0px 0px 0px 30px var(--color);
    }
}

对应HTML调整为:

<!-- 正确对勾 -->
<svg class="checkmark success" viewBox="0 0 52 52">
  <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/>
  <path class="checkmark__icon" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
</svg>

<!-- 错误叉号 -->
<svg class="checkmark error" viewBox="0 0 52 52">
  <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/>
  <path class="checkmark__icon" fill="none" d="M14.1 14.1l23.8 23.8 m0,-23.8 l-23.8,23.8"/>
</svg>

后续要新增其他颜色的校验动画,仅需新增对应类名定义--color变量即可,无需重复写动画和基础样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:54:05