如何实现父元素hover时统一加快所有子元素的独立动画速度?
实现父元素hover时同步加快所有子元素动画速度
核心思路是利用CSS变量统一控制动画参数,通过父元素的hover状态修改变量值,让所有子元素的动画同步加速,同时保留各自的关键帧效果。
具体实现步骤
- 定义CSS变量存储基础动画时长,所有子元素的动画时长、延迟都基于该变量设置
- 给父元素
.m添加hover状态,修改变量值缩短动画时长,实现整体加速 - 将动画延迟转换为基础时长的比例值,确保hover时各子元素的动画节奏保持一致
修改后的完整代码
CSS代码
body { padding: 300px; background-color: rgb(15, 19, 24); } /* 定义基础动画时长变量,默认1.8s */ .m { display: flex; justify-content: center; align-items: center; --anim-duration: 1.8s; } /* 父元素hover时,缩短动画时长实现加速 */ .m:hover { --anim-duration: 0.6s; } .m1 { width: 100px; height: 100px; background-color: rgb(255, 191, 29); border-radius: 100px; z-index: 2; /* 动画时长用变量,延迟为基础时长的0.666倍(对应原1.2s/1.8s的比例) */ animation: Pulses2 var(--anim-duration) ease calc(var(--anim-duration) * 0.666) infinite normal both; } .m2 { position: absolute; width: 100px; height: 100px; background-color: rgb(255, 191, 29); border-radius: 100px; z-index: 1; /* 延迟为基础时长的0.555倍(对应原1s/1.8s的比例) */ animation: Pulses1 var(--anim-duration) ease-out calc(var(--anim-duration) * 0.555) infinite normal forwards; } .m4 { position: absolute; width: 100px; height: 100px; background-color: rgb(255, 191, 29); border-radius: 100px; z-index: 0; /* 延迟为基础时长的0.777倍(对应原1.4s/1.8s的比例) */ animation: Pulses1 var(--anim-duration) ease-out calc(var(--anim-duration) * 0.777) infinite normal forwards; } .m3 { position: absolute; width: 100px; height: 100px; background-color: rgb(255, 241, 227); border-radius: 100px; z-index: -2; filter: blur(6px); /* 延迟为基础时长的0.555倍(对应原1s/1.8s的比例) */ animation: Pulses3 var(--anim-duration) ease calc(var(--anim-duration) * 0.555) infinite normal forwards; } @keyframes Pulses1 { from { transform: scale(0%); opacity: 100%; } to { transform: scale(280%); opacity: 0%; } } @keyframes Pulses2 { 0% { background-color: rgb(255, 191, 29); transform: scale(100%); } 50% { background-color: rgb(255, 243, 139); transform: scale(115%); } 100% { background-color: rgb(255, 191, 29); transform: scale(100%); } } @keyframes Pulses3 { 0% { transform: scale(990%); opacity: 0%; background-color: rgb(255, 176, 97); } 20% { opacity: 0%; } 50% { transform: scale(400%); opacity: 2%; background-color: rgb(255, 176, 97); } 70% { opacity: 0%; } 100% { transform: scale(700%); opacity: 0%; background-color: rgb(255, 196, 57); } }
HTML代码(无需修改)
<div class="m"> <div class="m1"></div> <div class="m2"></div> <div class="m3"></div> <div class="m4"></div> </div>
关键细节说明
- 移除了原代码中
.m *和.m *:hover的过渡样式,避免子元素单独响应hover的干扰 - 通过
--anim-duration变量统一控制所有子元素的动画时长,父元素hover时变量值从1.8s改为0.6s,所有子元素动画同步加速 - 动画延迟使用比例计算,保证hover时各子元素的动画节奏和原效果一致
- 所有子元素的关键帧动画完全保留,确保各自的独特视觉效果不受影响
内容的提问来源于stack exchange,提问作者Anhad Sharma
相关产品推荐
相关产品推荐

