CSS动画点击暂停无法停在当前位置,每次重新播放都从头开始如何解决?
问题根因
- 你混淆了CSS Transition和CSS Animation的适用属性:
animation-play-state、animation-fill-mode是专门给@keyframes定义的CSS动画使用的,你当前实现动画用的是transition过渡,这两个属性完全不会生效。 - 类名切换逻辑错误:暂停时直接移除了
.animated类替换成.noo类,相当于直接删除了过渡规则和最终背景位置定义,元素会自动回弹到默认的background-position: 100%状态,自然无法保留当前播放进度。 - CSS选择器书写错误:
.noo >是无效选择器,多了多余的子选择符>,哪怕属性是有效的也匹配不到目标元素。
修复方案
1. 修改CSS规则
将过渡逻辑放到目标元素的默认样式中,用状态类控制过渡的运行/暂停:
button { background-color: darkgreen; /* Green */ border-radius: 50px; border: none; color: white; padding: 13px 50px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; box-shadow: 0 3px 3px 0 rgba(0,0,0,0.4), 0 2px 1px rgba(0,0,0,0.1); } button:hover{ background-color: green; /* Green */ border-radius: 50px; border: none; color: white; padding: 13px 50px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; cursor: pointer; box-shadow: 0 6px 6px 0 rgba(0,0,0,0.25), 0 0 4px 2px rgba(0,0,0,0.05); transform: translateY(-2px); } p { position: relative; display: inline-block; font-size: 18px; font-weight: 80; color: black; overflow: hidden; background: linear-gradient(to right, darkgreen, darkgreen 50%, black 50%); background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-size: 200% 100%; background-position: 100%; /* 过渡规则移到默认样式,默认暂停状态 */ transition: background-position 9000ms linear; transition-play-state: paused; -webkit-transition-play-state: paused; } /* 运行状态类 */ .animated { transition-play-state: running; -webkit-transition-play-state: running; background-position: 0 100%; } /* 暂停状态类 */ .paused { transition-play-state: paused; -webkit-transition-play-state: paused; }
2. 修改JS逻辑
不再直接替换类名,改为通过增删暂停类控制动画状态:
const audio = document.getElementById("audio"); const target = document.getElementById('target'); // 标记是否是首次播放 let isFirstPlay = true; function ani(){ audio.play(); // 首次播放添加动画类 if (isFirstPlay) { target.classList.add('animated'); isFirstPlay = false; return; } // 非首次播放移除暂停类即可继续播放 target.classList.remove('paused'); } function ani2(){ audio.pause(); // 添加暂停类保留当前进度 target.classList.add('paused'); }
3. HTML部分
原有HTML代码无需修改,直接复用即可。
如果需要兼容不支持transition-play-state的旧版本浏览器,可以在暂停时通过getComputedStyle(target).backgroundPositionX获取当前的背景位置,直接赋值给元素的行内样式,下次播放时重新计算剩余过渡时长即可。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

