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

如何无JS实现CSS动画播放暂停,暂停时不返回初始状态

Pure CSS Solution for Animation Pause/Resume Without Resetting

Got it, let's fix this pure CSS animation pause/resume issue. The problem with your original code is that you're adding the animation only when the checkbox is checked—so when you uncheck it (pause), the animation gets removed entirely, which resets the progress bar back to width 0.

Instead, we need to keep the animation attached to the element at all times, and just toggle its play state using animation-play-state. Here's the corrected implementation:

<style>
#play { display: none; } 

#play+label[for=play] { 
  display: inline-block; 
  color: #fff; 
  cursor: pointer; 
  font-size: 13px; 
  z-index: 99; 
  padding: 5px; 
  background: #37A000; 
  margin-bottom: 15px; 
} 

#play+label[for=play]>span:nth-of-type(2), 
#play:checked+label[for=play]>span:nth-of-type(1) { 
  display: none; 
} 

#play:checked+label[for=play] { 
  background: tomato; 
} 

#play:checked+label[for=play]>span:nth-of-type(2) { 
  display: block; 
} 

.progress { 
  height: 15px; 
  background: #555; 
  position: relative; 
} 

.progress:after { 
  width: 0; 
  content: ''; 
  position: absolute; 
  top: 0; 
  left: 0; 
  height: 100%; 
  background: #37A000; 
  /* Keep animation attached permanently */
  animation: animProgress 7s linear infinite; 
  /* Start in paused state */
  animation-play-state: paused; 
} 

/* Toggle play state instead of adding/removing animation */
#play:checked+label[for=play]~.progress:after { 
  animation-play-state: running; 
} 

@keyframes animProgress { 
  100% { width: 100%; } 
} 
</style>

<input type="checkbox" name="play" id="play"> 
<label for="play"> 
  <span>Play</span> 
  <span>Pause</span> 
</label> 
<div class="progress"></div>

Key Changes Explained:

  • Permanent Animation Attachment: We moved the animation property to the base .progress:after rule, so the animation is always present on the element—never removed.
  • Default Paused State: The animation starts with animation-play-state: paused so it doesn't run until the user clicks Play.
  • Toggle Play State: Instead of adding/removing the animation when the checkbox is toggled, we only switch animation-play-state between running (Play) and paused (Pause).

How It Works:

When you click Pause, the animation stops at its current frame—so the progress bar stays exactly where it is. Click Play again, and it resumes animating from that exact position. Since we kept infinite in the animation, it will loop continuously once playing. If you want the animation to stop at 100% instead of looping, just replace infinite with forwards in the animation declaration.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:24:46