JavaScript控制CSS进度条暂停时animationPlayState不生效如何解决
问题解决方法
你操作的元素不对,CSS动画是绑定在进度条的.inner子节点上,你对外层#progressbar1设置animationPlayState当然没有效果,选中对应的子元素操作即可。
下面是包含暂停/继续切换、重置、自定义时长三个功能的完整实现代码:
修改后的HTML(增加控制按钮)
<div id="progressbar1"></div> <div style="text-align:center;margin-top:80px"> <button id="toggleBtn">暂停/继续</button> <button id="resetBtn">重置进度</button> <input type="number" id="customDuration" placeholder="输入时长(秒)" min="1"> <button id="setDurationBtn">设置新时长</button> </div>
无需修改原有CSS代码
修改后的JS代码
// 存储进度条inner元素、当前时长、回调函数,方便后续操作 let progressInner = null; let currentDuration = '180s'; let endCallback = null; function createProgressbar(id, duration, callback) { var progressbar = document.getElementById(id); // 先清空原有内容,避免重复添加inner progressbar.innerHTML = ''; progressbar.className = 'progressbar'; var progressbarinner = document.createElement('div'); progressbarinner.className = 'inner'; progressbarinner.style.animationDuration = duration; currentDuration = duration; endCallback = callback; if (typeof(callback) === 'function') { progressbarinner.addEventListener('animationend', callback); } progressbar.appendChild(progressbarinner); progressInner = progressbarinner; progressbarinner.style.animationPlayState = 'running'; } addEventListener('load', function() { createProgressbar('progressbar1', '180s', function() { window.location.replace("gotomypage.html"); }); // 原点击进度条暂停功能修复 document.getElementById('progressbar1').addEventListener("click", function() { console.log ('TEST - Stop Progressbar'); progressInner.style.animationPlayState = 'paused'; }); // 暂停/继续切换 document.getElementById('toggleBtn').addEventListener('click', function() { const currentState = progressInner.style.animationPlayState; progressInner.style.animationPlayState = currentState === 'running' ? 'paused' : 'running'; }) // 重置进度 document.getElementById('resetBtn').addEventListener('click', function() { createProgressbar('progressbar1', currentDuration, endCallback); }) // 自定义运行时长 document.getElementById('setDurationBtn').addEventListener('click', function() { const input = document.getElementById('customDuration'); const duration = parseInt(input.value.trim()); if (duration && duration > 0) { createProgressbar('progressbar1', `${duration}s`, endCallback); input.value = ''; } }) });
功能说明
- 暂停/继续:切换动画的
animationPlayState属性即可实现状态切换,操作对象必须是绑定了动画的.inner元素 - 重置:直接重新调用
createProgressbar方法初始化进度条即可回到初始状态 - 自定义时长:读取用户输入的秒数后,重新调用初始化方法传入新的时长参数即可
内容的提问来源于stack exchange,提问作者JoostVanPoppel
相关产品推荐
相关产品推荐

