jQuery动画循环与暂停实现:鼠标控制续播而非重启
实现hover动画的暂停/续播+循环效果
我明白你要的效果:鼠标移上去动画启动,移开就暂停,再移上去接着上次的位置播,而且动画结束后自动循环。咱们一步步来搞定这个需求:
核心思路
要做到续播,关键是记录动画的当前进度,下次播放时从这个进度点开始。结合CSS动画的animation-play-state和JS来控制状态,比纯JS手写动画更流畅,也更易维护。
完整代码实现
HTML结构
<figure class="animated-figure"> <img src="your-image.jpg" alt="需要加动画的图片"> </figure>
CSS样式
.animated-figure { width: 300px; height: 200px; overflow: hidden; cursor: pointer; } .animated-figure img { width: 100%; height: 100%; object-fit: cover; /* 定义你的hover动画,这里用缩放+透明度做示例,你可以替换成自己的动画 */ animation: hoverAnim 3s ease-in-out infinite paused; } /* 自定义动画,按需修改 */ @keyframes hoverAnim { 0% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.2); opacity: 0.8; } 100% { transform: scale(1); opacity: 1; } }
JavaScript控制逻辑
$('figure.animated-figure').each(function() { const $figure = $(this); const $img = $figure.find('img'); const animationDuration = 3; // 对应CSS里的动画时长,单位秒 let lastProgress = 0; // 存储上次暂停的动画进度 $figure.mouseenter(function() { // 计算偏移时间,让动画从暂停处直接启动 const delay = -(lastProgress * animationDuration); $img.css({ 'animation-delay': `${delay}s`, 'animation-play-state': 'running' }); }); $figure.mouseleave(function() { // 获取当前动画已播放的时间,计算进度 const computedStyle = window.getComputedStyle($img[0]); const elapsedTime = parseFloat( computedStyle.animationPlayState === 'running' ? computedStyle.animationElapsedTime : 0 ); // 取模处理循环场景,确保进度始终在0-1之间 lastProgress = (elapsedTime % animationDuration) / animationDuration; $img.css('animation-play-state', 'paused'); }); });
关键细节说明
- CSS初始状态:给动画默认设置
paused,确保页面加载时动画不自动播放;infinite属性保证动画结束后自动循环。 - 进度记录:鼠标离开时,通过
getComputedStyle获取animationElapsedTime(动画已播放的时长),计算出0到1之间的进度值并存储。 - 续播实现:再次hover时,用负的
animation-delay让动画直接跳转到上次暂停的位置,再启动播放状态。 - 循环兼容:用
% animationDuration处理已播放时间,哪怕动画已经循环过N次,进度计算依然准确。
如果你的原动画时长、动画名称不同,只需要对应修改CSS里的animation属性和JS里的animationDuration值就可以无缝适配。
内容的提问来源于stack exchange,提问作者guillaumeb
相关产品推荐
相关产品推荐

