如何无JS实现CSS动画播放暂停,暂停时不返回初始状态
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
animationproperty to the base.progress:afterrule, so the animation is always present on the element—never removed. - Default Paused State: The animation starts with
animation-play-state: pausedso 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-statebetweenrunning(Play) andpaused(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

