如何创建带有多值的自定义圆形进度指示器?
实现圆形进度指示器的几种方案
根据你提供的样式需求,这里给出三种常用的实现方式,涵盖静态展示和动态控制场景:
方案一:纯CSS静态进度指示器
适合不需要动态修改进度的场景,代码简洁无需JS:
<div class="circular-progress"> <div class="progress-ring"></div> <span class="progress-text">75%</span> </div>
.circular-progress { position: relative; width: 120px; height: 120px; } .progress-ring { position: absolute; width: 100%; height: 100%; border-radius: 50%; /* 锥状渐变实现进度,第一个值为进度百分比 */ background: conic-gradient(#4CAF50 75%, #e0e0e0 0); /* 径向遮罩挖空中间,形成环形效果 */ mask: radial-gradient(transparent 55%, black 0); -webkit-mask: radial-gradient(transparent 55%, black 0); } .progress-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 18px; font-weight: bold; }
方案二:CSS+JS动态控制进度
支持根据业务逻辑实时更新进度值:
<div class="circular-progress"> <div class="progress-ring"></div> <span class="progress-text" id="progressText">0%</span> </div> <!-- 示例按钮,实际场景可根据业务触发更新 --> <button onclick="updateProgress(60)">设置为60%</button>
.circular-progress { position: relative; width: 120px; height: 120px; } .progress-ring { position: absolute; width: 100%; height: 100%; border-radius: 50%; /* 使用CSS变量动态控制进度 */ background: conic-gradient(#4CAF50 var(--progress, 0%), #e0e0e0 0); mask: radial-gradient(transparent 55%, black 0); -webkit-mask: radial-gradient(transparent 55%, black 0); transition: background 0.3s ease; } .progress-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 18px; font-weight: bold; }
function updateProgress(percent) { const progressRing = document.querySelector('.progress-ring'); const progressText = document.getElementById('progressText'); // 更新CSS变量 progressRing.style.setProperty('--progress', `${percent}%`); // 更新文本 progressText.textContent = `${percent}%`; }
方案三:SVG实现
SVG天生适合绘制矢量图形,进度控制逻辑更直观:
<svg width="120" height="120" viewBox="0 0 120 120"> <!-- 灰色背景环 --> <circle cx="60" cy="60" r="50" fill="none" stroke="#e0e0e0" stroke-width="10"/> <!-- 彩色进度环:stroke-dasharray为圆周长(2πr=314),stroke-dashoffset为未填充部分长度 --> <circle cx="60" cy="60" r="50" fill="none" stroke="#4CAF50" stroke-width="10" stroke-dasharray="314" stroke-dashoffset="78.5" stroke-linecap="round" transform="rotate(-90 60 60)"/> <!-- 中间百分比文本 --> <text x="60" y="65" text-anchor="middle" font-size="18" font-weight="bold">75%</text> </svg>
如果需要动态修改进度,可通过JS控制stroke-dashoffset:
function updateSvgProgress(percent) { const progressCircle = document.querySelector('svg circle:nth-child(2)'); const text = document.querySelector('svg text'); const circumference = 2 * Math.PI * 50; // 计算未填充部分的长度 const offset = circumference * (1 - percent / 100); progressCircle.style.strokeDashoffset = offset; text.textContent = `${percent}%`; }
内容的提问来源于stack exchange,提问作者Dhiraj
相关产品推荐
相关产品推荐

