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

为无限渐变动画添加暂停以优化网页性能

实现CSS渐变动画的暂停效果

针对你的性能优化需求,下面提供两种可行的修改方案,分别对应自动周期性暂停(让浏览器定时休息)和手动切换暂停/运行的场景:


方案一:自动周期性暂停(适配性能优化需求)

直接修改动画关键帧,让动画完成一次渐变过渡后,保持静止状态一段时间,再循环执行。这种方式兼容性最好,无需额外依赖。

修改后的完整CSS代码:

.css-selector {
    background: linear-gradient(270deg, #3adab1, #3a7bda, #853ada);
    background-size: 600% 600%;
    /* 总时长设为40s:30s执行渐变动画 + 10s静止暂停,可根据需求调整比例 */
    -webkit-animation: AnimationName 40s ease-in-out infinite;
    -moz-animation: AnimationName 40s ease-in-out infinite;
    animation: AnimationName 40s ease-in-out infinite;
}

@-webkit-keyframes AnimationName {
    0% { background-position: 0% 50%; }
    37.5% { background-position: 100% 50%; } /* 对应15s,完成一半过渡 */
    75% { background-position: 0% 50%; } /* 对应30s,完成完整渐变周期 */
    100% { background-position: 0% 50%; } /* 保持静止到40s,进入下一轮循环 */
}

@-moz-keyframes AnimationName {
    0% { background-position: 0% 50%; }
    37.5% { background-position: 100% 50%; }
    75% { background-position: 0% 50%; }
    100% { background-position: 0% 50%; }
}

@keyframes AnimationName {
    0% { background-position: 0% 50%; }
    37.5% { background-position: 100% 50%; }
    75% { background-position: 0% 50%; }
    100% { background-position: 0% 50%; }
}

你可以根据需求调整总时长和静止阶段的比例,比如把总时长设为50s,其中30s运行、20s暂停,只需将关键帧的75%改为60%即可。


方案二:手动切换暂停/运行状态

利用animation-play-state属性,通过类切换或交互事件控制动画的暂停与运行,适合需要用户主动触发暂停的场景。

方式1:通过CSS类切换

.css-selector {
    background: linear-gradient(270deg, #3adab1, #3a7bda, #853ada);
    background-size: 600% 600%;
    -webkit-animation: AnimationName 30s ease infinite;
    -moz-animation: AnimationName 30s ease infinite;
    animation: AnimationName 30s ease infinite;
    /* 默认运行状态 */
    -webkit-animation-play-state: running;
    -moz-animation-play-state: running;
    animation-play-state: running;
}

/* 添加.paused类时触发暂停 */
.css-selector.paused {
    -webkit-animation-play-state: paused;
    -moz-animation-play-state: paused;
    animation-play-state: paused;
}

/* 原关键帧保持不变 */
@-webkit-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@-moz-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}

使用时只需给目标元素添加/移除.paused类,即可切换动画状态。

方式2:交互触发(比如鼠标悬停暂停)

如果需要鼠标悬停时暂停动画,直接添加以下CSS即可:

.css-selector:hover {
    -webkit-animation-play-state: paused;
    -moz-animation-play-state: paused;
    animation-play-state: paused;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:37:26