Lottie动画播放/暂停切换按钮无法正常实现暂停功能
Lottie播放/暂停按钮失效问题修复
问题说明
制作了基于Font Awesome图标的Lottie动画播放/暂停切换按钮,动画未激活时显示播放图标,激活时显示暂停图标。目前播放功能正常,但暂停功能完全失效,浏览器控制台无任何报错信息。
错误原因
原代码中点击事件的判断逻辑错误:使用if (animation.pause)来判断状态,而animation.pause是Lottie实例的方法,只要方法存在就会返回true,导致永远只会执行播放逻辑,根本不会进入暂停分支。
正确的判断应该使用Lottie实例提供的isPaused属性,该属性会返回布尔值,准确反映当前动画是否处于暂停状态。
另外,原按钮使用<a>标签,点击时会触发默认的锚点跳转行为,可能干扰按钮功能,需要阻止该默认行为。
修复后的完整代码
<!DOCTYPE html> <html dir="ltr" lang="en"> <head> <title>Lottie Player Web Button Component</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.5.3/lottie_svg.min.js"></script> <script src="https://kit.fontawesome.com/8a60cdf3a9.js" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://use.typekit.net/yil7vfv.css"> <style> body { font-family: Roboto; background: #fff; display: flex; flex-direction: column; justify-content: center; align-items: center; height: 40vh; } .fa-regular { color: #666666; font-size:30px; } .my-icon { vertical-align: middle; font-size: 24px; } .my-text { font-family: "Courier-new"; } .my-fancy-container { border: none; border-radius: 0; display: inline-block; margin: 60px; padding: 10px; } #play-button { padding-right: 16px; } </style> </head> <body> <div id="lottie-animation" background="transparent" speed="0.5" style="width: 400px; height: 400px;"></div> <div> <a href="#" id="playPauseBtn"><i class="fa-regular fa-circle-play"></i></a> </div> <script> // Initialize Lottie player const animation = lottie.loadAnimation({ container: document.getElementById('lottie-animation'), renderer: 'svg', loop: true, autoplay: false, // Set to false to initially not play path: 'https://assets1.lottiefiles.com/datafiles/HN7OcWNnoqje6iXIiZdWzKxvLIbfeCGTmvXmEm1h/data.json' // Replace with your animation file }); // Get buttons const playPauseBtn = document.getElementById("playPauseBtn"); // Play button functionality playPauseBtn.addEventListener("click", (event) => { // 阻止<a>标签默认跳转行为 event.preventDefault(); if (animation.isPaused) { animation.play(); playPauseBtn.innerHTML = '<i class="fa-regular fa-circle-pause"></i>'; } else { animation.pause(); playPauseBtn.innerHTML = '<i class="fa-regular fa-circle-play"></i>'; } }); </script> </body> </html>
关键修改点
- 将判断条件从
animation.pause改为animation.isPaused,准确获取当前动画的暂停状态 - 在点击事件中添加
event.preventDefault(),阻止<a>标签的默认锚点跳转行为,避免不必要的页面滚动
内容的提问来源于stack exchange,提问作者netniks
相关产品推荐
相关产品推荐

