如何使用HTML、CSS、JavaScript实现符合预期样式的动态环形进度条

预期效果

当前实现效果
核心问题点
- 进度动画和数值逻辑不同步:CSS默认配置的动画是8秒跑满360度对应100%进度,而JS计数器仅到65%就停止,总耗时仅5.2秒,二者完全不匹配
- 进度端点无圆角:目标进度条两端为圆润效果,当前实现未给进度条添加圆角属性
- 未填充区域样式错误:当前未填充进度条是纯白色,和页面背景色差过大,不符合预期样式
修改后完整代码
HTML
<div class="circular"> <div class="inner"></div> <div class="number">100%</div> <div class="circle"> <div class="bar left"> <div class="progress"></div> </div> <div class="bar right"> <div class="progress"></div> </div> </div> </div>
CSS
*{ margin: 0; padding: 0; font-family: 'Arial', sans-serif; } html, body{ display:grid; height:100%; text-align: center; place-items: center; background: #dde6f0; } .circular{ height:120px; width: 120px; position: relative; transform:scale(2); } .circular .inner{ position: absolute; z-index: 6; top: 50%; left: 50%; height: 80px; width: 80px; margin: -40px 0 0 -40px; background: #dde6f0; border-radius: 100%; } .circular .number{ position: absolute; top:50%; left:50%; transform: translate(-50%, -50%); z-index:10; font-size:18px; font-weight:500; color:#4158d0; } .circular .bar{ position: absolute; height: 100%; width: 100%; background: #d0d8e2; -webkit-border-radius: 100%; clip: rect(0px, 120px, 120px, 70px); } .circle .bar .progress{ position: absolute; height: 100%; width: 100%; -webkit-border-radius: 100%; clip: rect(0px, 70px, 120px, 0px); background: #FF6600; border-radius: 100%; } .circle .left .progress{ z-index:1; animation: left 2.6s linear both; } @keyframes left{ 100%{ transform: rotate(180deg); } } .circle .right { transform: rotate(180deg); z-index:3; } .circle .right .progress{ animation: right 2.6s linear both; animation-delay:2.6s; } @keyframes right{ 100%{ transform: rotate(54deg); } }
JavaScript
const numb = document.querySelector(".number"); let counter = 0; const timer = setInterval(() => { if(counter == 65 ){ clearInterval(timer); }else{ counter+=1; numb.textContent = counter + "%"; } }, 80);
修改后进度动画和数值会完全同步,进度端点为圆角,未填充区域为浅灰色,符合预期样式。
内容的提问来源于stack exchange,提问作者Elex Promise
相关产品推荐
相关产品推荐

