JavaScript原生实现进度条需三步:1. HTML构建容器与进度条结构;2. CSS设置容器宽高、隐藏溢出并为进度条添加宽度过渡;3. JS用setInterval定时更新style.width百分比值,达目标后clearInterval防泄漏。

用 JavaScript 实现进度条并定时更新宽度,核心是动态修改元素的 width 样式,并配合定时器(如 setInterval)逐步推进。不需要第三方库,原生 JS 就能轻松搞定。
先写一个简单但语义清晰的结构:
其中 .progress-container 是外层固定宽高的盒子,.progress-bar 是内部随进度伸缩的条。
立即学习“Java免费学习笔记(深入)”;
关键点:设置容器为相对定位,进度条为绝对定位或 inline-block;宽度用百分比,高度/颜色按需定制:
.progress-container {
width: 300px;
height: 20px;
background-color: #e0e0e0;
border-radius: 10px;
overflow: hidden;
}
.progress-bar {
height: 100%;
background-color: #4caf50;
width: 0%;
transition: width 0.3s ease; /* 加个平滑过渡更自然 */
}
获取 DOM 元素,设定目标值(比如 100%),再用 setInterval 每隔一段时间增加一点宽度:
const progressBar = document.getElementById('progressBar');
let currentWidth = 0;
const targetWidth = 100;
const step = 2; // 每次增加 2%
const intervalTime = 100; // 每 100ms 更新一次
const timer = setInterval(() => {
if (currentWidth >= targetWidth) {
clearInterval(timer);
return;
}
currentWidth += step;
progressBar.style.width = currentWidth + '%';
}, intervalTime);
style.width 直接设百分比字符串(别漏掉 '%')clearInterval,避免内存泄漏或超限让进度条更实用:
startProgress(el, total = 100, duration = 3000),用时间而非步长控制速度fetch 或上传事件,用实际加载量(如 event.loaded / event.total)驱动 width,更真实progressBar.textContent = Math.round(currentWidth) + '%'(注意兼容性,建议另加 <span></span>)基本上就这些。不复杂但容易忽略细节——比如没清定时器、忘了加单位、CSS 没设 overflow: hidden 导致撑出边框。照着试一遍,马上就能跑起来。
以上就是JavaScript中如何实现进度条_定时更新宽度的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号