能否让CSS无限循环关键帧动画在指定位置或事件触发时停在当前帧?
动画暂停在当前状态的解决方案
嘿,我来帮你搞定这个动画暂停的问题!你现在遇到的情况是,用animation-iteration-count: 0停止动画时,它会直接跳回初始状态,这显然不是你想要的幸运转盘效果——咱们要的是停在哪就保持在哪对吧?
其实CSS早就提供了完美的解决方案:animation-play-state属性,专门用来控制动画的播放和暂停,而且暂停时会精确冻结在当前的动画进度位置,完全符合你的需求。
问题根源解释
你之前用animation-iteration-count来停止动画的思路有问题:这个属性控制的是动画循环的执行次数,设置为0相当于让浏览器完全放弃执行动画,自然会把元素重置到动画开始前的初始状态。而animation-play-state是直接干预动画的运行状态,暂停时不会改变元素当前的样式计算结果。
修改后的完整代码
HTML部分
<div id='wrap'> <div id='left-eye'> </div> <div id='right-eye'> </div> <div id='mouth'> </div> </div> <input type='button' value='start' onClick="document.getElementById('wrap').style.animationPlayState = 'running';"> <input type='button' value='stop' onClick="document.getElementById('wrap').style.animationPlayState = 'paused';">
CSS部分
#wrap { background-color: yellow; position: relative; top: 0px; width: 100px; height: 100px; border-radius: 50px; box-sizing: border-box; transition: 700ms linear; /* 初始设置为无限循环但暂停状态,页面加载后不会自动转动 */ animation-duration: 1200ms; animation-name: rotateDiv; animation-iteration-count: infinite; animation-timing-function: linear; animation-play-state: paused; } #wrap:hover { background-color: orange; } #mouth { background-color: transparent; position: absolute; border-left: 4px solid black; border-right: 4px solid black; border-bottom: 4px solid black; border-radius: 0 0 60px 60px; height: 30px; width: 60px; top: 52px; left: 20px; box-sizing: border-box; display: inline-block; overflow: hidden; padding: 0; } #left-eye { position: absolute; background-color: black; border-radius: 50%; width: 8px; height: 16px; box-sizing: border-box; left: 30px; top: 25px; display: inline-block; overflow: hidden; padding: 0; } #right-eye { position: absolute; background-color: black; border-radius: 50%; width: 8px; height: 16px; box-sizing: border-box; top: 25px; right: 30px; display: inline-block; overflow: hidden; padding: 0; } @keyframes rotateDiv { from { -ms-transform: rotate(0deg); /* IE 9 兼容 */ -webkit-transform: rotate(0deg); /* Safari 兼容 */ transform: rotate(0deg); } to { -ms-transform: rotate(360deg); /* IE 9 兼容 */ -webkit-transform: rotate(360deg); /* Safari 兼容 */ transform: rotate(360deg); } }
核心细节说明
animation-play-state: paused:这是实现需求的关键,设置后动画会立即停止在当前的旋转角度,不管此时元素是正立还是倒置,都会保持这个状态直到你再次点击start按钮。- 初始状态优化:我把
#wrap的初始动画设置为无限循环但暂停,这样页面加载后转盘不会自动转动,更符合常规的交互逻辑。 - 兼容性:这个属性支持所有现代浏览器,包括IE10及以上版本,完全满足日常开发的需求。
内容的提问来源于stack exchange,提问作者2x2p
相关产品推荐
相关产品推荐

