如何实现支持正负值及逆时针方向的环形进度指示器?
实现可反向运行的环形进度指示器
完全可以实现这种正负值区分方向和颜色的环形进度指示器,下面是基于HTML+CSS+JavaScript的具体实现方案:
实现代码
HTML结构
<div class="progress-container"> <svg class="progress-ring" width="200" height="200"> <!-- 背景灰色环 --> <circle class="progress-bg" cx="100" cy="100" r="90" /> <!-- 动态变化的进度环 --> <circle class="progress-fill" cx="100" cy="100" r="90" /> </svg> <input type="number" id="valueInput" placeholder="输入-100到100的数值" /> </div>
CSS样式
.progress-container { position: relative; display: flex; flex-direction: column; align-items: center; gap: 16px; } .progress-ring { /* 初始旋转使环形起点在顶部 */ transform: rotate(-90deg); } .progress-bg { fill: none; stroke: #e5e7eb; stroke-width: 10; } .progress-fill { fill: none; stroke-width: 10; stroke-linecap: round; /* 添加过渡动画让进度变化更平滑 */ transition: stroke-dashoffset 0.5s ease, stroke 0.3s ease; }
JavaScript逻辑
const progressFill = document.querySelector('.progress-fill'); const valueInput = document.getElementById('valueInput'); const radius = 90; const circumference = 2 * Math.PI * radius; // 初始化进度环的 dash 参数 progressFill.style.strokeDasharray = `${circumference}`; progressFill.style.strokeDashoffset = `${circumference}`; // 监听输入框变化实时更新进度 valueInput.addEventListener('input', updateProgress); function updateProgress() { let value = parseFloat(valueInput.value); if (isNaN(value)) return; // 限制数值范围在 -100 到 100 之间(可根据需求修改) value = Math.max(-100, Math.min(100, value)); const progressRatio = Math.abs(value) / 100; const targetOffset = circumference * (1 - progressRatio); if (value >= 0) { // 正值:顺时针转动,绿色进度环 progressFill.style.stroke = '#10b981'; progressFill.style.transform = 'rotate(0deg)'; progressFill.style.strokeDashoffset = `${targetOffset}`; } else { // 负值:逆时针转动,红色进度环(通过旋转180度实现反向) progressFill.style.stroke = '#ef4444'; progressFill.style.transform = 'rotate(180deg)'; progressFill.style.strokeDashoffset = `${targetOffset}`; } }
核心逻辑说明
- 环形绘制:使用SVG的
<circle>元素实现环形,背景环固定为灰色,进度环通过stroke-dasharray和stroke-dashoffset控制显示长度。 - 方向控制:正值时保持进度环默认方向(顺时针);负值时将进度环旋转180度,配合
stroke-dashoffset的变化实现逆时针效果。 - 颜色区分:直接通过修改
stroke属性设置绿色(正值)和红色(负值)。 - 平滑过渡:添加CSS过渡动画,让进度变化和颜色切换更自然。
自定义调整点
- 修改SVG的
width/height和r(半径)可以调整环形的大小。 - 调整
stroke-width可以改变环形的粗细。 - 修改
transition参数可以调整动画速度。 - 调整数值范围限制(当前是-100到100)可以适配不同的业务场景。
内容的提问来源于stack exchange,提问作者lovecode
相关产品推荐
相关产品推荐

