如何在ReactJS中实现带内部倒计时的填充式进度圈?求解决方案
Got it! 不用费劲找插件啦,咱们用原生HTML+CSS+JavaScript就能完美实现这个带倒计时的进度圈效果。我给你准备了一个完整可运行的示例,注释都写得明明白白,你直接拿去改参数就能适配自己的场景~
实现思路
- 用SVG的
<circle>元素绘制进度圈:一个灰色的背景圈,叠上一个彩色的进度圈 - 通过SVG的
stroke-dasharray和stroke-dashoffset属性控制进度圈的显示长度,这俩是实现环形进度动画的核心 - 用JavaScript维护倒计时状态,实时计算剩余时间占总时长的比例,同步更新进度圈的偏移量
完整代码示例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>倒计时进度圈</title> <style> .countdown-container { position: relative; width: 200px; height: 200px; margin: 50px auto; } /* SVG容器旋转,让进度从顶部开始 */ .progress-circle { width: 100%; height: 100%; transform: rotate(-90deg); } /* 灰色背景圈 */ .circle-bg { fill: none; stroke: #eee; stroke-width: 10; } /* 彩色进度圈 */ .circle-progress { fill: none; stroke: #4CAF50; stroke-width: 10; stroke-linecap: round; /* 进度条末端做圆角处理 */ transition: stroke-dashoffset 0.1s linear; /* 让进度变化更平滑 */ } /* 居中显示的倒计时文本 */ .countdown-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 32px; font-weight: bold; color: #333; } </style> </head> <body> <div class="countdown-container"> <svg class="progress-circle" viewBox="0 0 100 100"> <!-- 背景圈 --> <circle class="circle-bg" cx="50" cy="50" r="40"></circle> <!-- 动态变化的进度圈 --> <circle class="circle-progress" cx="50" cy="50" r="40"></circle> </svg> <!-- 显示倒计时数字 --> <div class="countdown-text" id="countdownText">10</div> </div> <script> // 可自定义的配置参数 const totalSeconds = 10; // 总倒计时时长(秒) let remainingSeconds = totalSeconds; // 获取DOM元素 const progressCircle = document.querySelector('.circle-progress'); const countdownText = document.getElementById('countdownText'); // 计算圆形的周长(公式:2πr) const circleCircumference = 2 * Math.PI * 40; // 初始化进度圈的虚线参数 progressCircle.style.strokeDasharray = circleCircumference; progressCircle.style.strokeDashoffset = circleCircumference; // 更新进度和倒计时的核心函数 function updateCountdown() { // 计算剩余时间占总时长的比例 const progressRatio = remainingSeconds / totalSeconds; // 更新进度圈的偏移量:剩余比例越大,偏移量越大,显示的进度越少 progressCircle.style.strokeDashoffset = circleCircumference * progressRatio; // 更新倒计时文本 countdownText.textContent = remainingSeconds; // 倒计时结束后的处理逻辑 if (remainingSeconds === 0) { clearInterval(countdownInterval); alert('倒计时结束!'); // 这里可以添加你需要的结束逻辑,比如重置进度圈或触发其他操作 } remainingSeconds--; } // 初始化显示 updateCountdown(); // 每秒执行一次更新 const countdownInterval = setInterval(updateCountdown, 1000); </script> </body> </html>
关键细节说明
- SVG进度圈核心:
stroke-dasharray设为圆形周长,让进度圈变成一段完整的虚线;stroke-dashoffset控制虚线的偏移位置,偏移量越小,显示的进度部分越多,刚好和倒计时递减的逻辑匹配。 - 自定义调整指南:
- 修改
totalSeconds可以设置任意倒计时时长 - 调整
.circle-progress的stroke属性能更换进度圈颜色 - 修改
stroke-width可以改变进度圈的粗细 - 调整
.countdown-container的宽高能缩放整个组件的大小
- 修改
内容的提问来源于stack exchange,提问作者PCK
相关产品推荐
相关产品推荐

