寻求纯CSS解决方案:按钮动画hover时中途暂停,移出后恢复
纯CSS实现按钮动画Hover中途暂停且不自动启动
解决方案核心
通过CSS的animation-play-state属性控制动画的暂停与播放,同时将动画初始状态设为暂停,避免页面加载时自动运行,再结合伪类实现Hover时暂停、移出后恢复的逻辑。
完整代码实现
HTML
<h2>Hover 时中途暂停动画,移出后恢复</h2> <button type="button" class="btn-animation btn-primary">Hover 暂停</button>
CSS
/* 按钮基础样式 */ .btn-primary { padding: 12px 24px; border: none; border-radius: 4px; background-color: #007bff; color: #fff; font-size: 16px; cursor: pointer; position: relative; overflow: hidden; } /* 动画载体伪元素 */ .btn-animation::before { content: ""; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background-color: rgba(255, 255, 255, 0.2); /* 定义动画:从左滑到右,无限循环 */ animation: slide 2s linear infinite; /* 初始状态暂停动画,避免页面加载自动运行 */ animation-play-state: paused; } /* 鼠标移出按钮时,恢复动画播放 */ .btn-animation:not(:hover)::before { animation-play-state: running; } /* 鼠标Hover按钮时,暂停动画在当前帧 */ .btn-animation:hover::before { animation-play-state: paused; } /* 动画关键帧定义 */ @keyframes slide { to { left: 100%; } }
关键细节说明
- 初始暂停动画:通过
animation-play-state: paused确保页面加载时动画处于停止状态,不会自动启动。 - Hover暂停逻辑:利用
:hover伪类将动画状态切换为暂停,此时动画会停在当前执行的帧位置。 - 移出恢复播放:通过
:not(:hover)伪类在鼠标离开按钮时,将动画状态切回播放,动画会从暂停的位置继续执行。 - 自定义动画:你可以替换
@keyframes slide里的逻辑,改成你需要的动画效果(比如颜色渐变、缩放等),只要保持animation-play-state的控制逻辑即可。
内容的提问来源于stack exchange,提问作者Fawn
相关产品推荐
相关产品推荐

