进度条学习笔记

1. 简介

进度条是一种在用户界面中显示操作进度的控件,通常用于表示长时间运行的任务或操作的进度。它可以显示百分比、剩余时间和已完成的步骤等信息,让用户了解当前操作的状态,从而提高用户体验和交互性。

2. 常见的进度条类型

2.1 按钮进度条

按钮进度条通常用于表示单个任务的进度,如上传文件或下载内容。它会在按钮上显示一个逐渐填充的进度条,并在任务完成后自动消失。

htmlCopy Code
<button id="btn">上传文件</button> <script> const btn = document.querySelector('#btn'); btn.addEventListener('click', () => { btn.disabled = true; const progress = document.createElement('progress'); btn.parentNode.insertBefore(progress, btn); // 模拟上传文件并更新进度 let percent = 0; const timer = setInterval(() => { percent++; progress.value = percent; if (percent >= 100) { clearInterval(timer); btn.disabled = false; progress.parentNode.removeChild(progress); } }, 50); }); </script>

2.2 径向进度条

径向进度条是一种环形进度条,通常用于表示多个任务的进度。它可以分为多个部分,每个部分表示一个任务的进度,并根据任务的完成情况自动更新进度。

htmlCopy Code
<svg viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" stroke="#ccc" stroke-width="10" fill="none" /> <circle id="part1" cx="50" cy="50" r="40" stroke="#f44336" stroke-width="10" fill="none" stroke-dasharray="0 251.2" transform="rotate(-90, 50, 50)" /> <circle id="part2" cx="50" cy="50" r="40" stroke="#673ab7" stroke-width="10" fill="none" stroke-dasharray="0 125.6" transform="rotate(-90, 50, 50)" /> <circle id="part3" cx="50" cy="50" r="40" stroke="#4caf50" stroke-width="10" fill="none" stroke-dasharray="0 62.8" transform="rotate(-90, 50, 50)" /> <circle cx="50" cy="50" r="34" stroke="#fff" stroke-width="2" fill="none" /> </svg> <script> const part1 = document.querySelector('#part1'); const part2 = document.querySelector('#part2'); const part3 = document.querySelector('#part3'); // 模拟多个任务并更新进度 let count1 = 0; const timer1 = setInterval(() => { count1++; part1.setAttribute('stroke-dasharray', `${count1 * 2.512} 251.2`); if (count1 >= 100) clearInterval(timer1); }, 50); let count2 = 0; const timer2 = setInterval(() => { count2++; part2.setAttribute('stroke-dasharray', `${count2 * 1.256} 125.6`); if (count2 >= 50) clearInterval(timer2); }, 50); let count3 = 0; const timer3 = setInterval(() => { count3++; part3.setAttribute('stroke-dasharray', `${count3 * 0.628} 62.8`); if (count3 >= 25) clearInterval(timer3); }, 50); </script>

3. 总结

进度条是一种十分实用的控件,可以在用户界面中优化操作体验和可用性。通过学习不同类型的进度条的实现原理,我们可以更加灵活地应用它们到具体的项目中,提高项目的效率和用户满意度。