css 属性 strokeDasharray
实现功能:
代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
.progress-ring {
width: 200px;
height: 200px;
position: relative;
}
.progress-ring .circle {
fill: none;
stroke: #ddd;
stroke-width: 20;
}
.progress-ring .progress {
fill: none;
stroke: #0d7137;
stroke-width: 20;
stroke-dasharray: 0, 1000;
stroke-linecap: round;
transition: stroke-dasharray 0.5s ease-in-out;
}
</style>
</head>
<body>
<div class="progress-ring">
<svg viewBox="0 0 100 100">
<circle class="circle" cx="50" cy="50" r="40">22</circle>
<circle class="progress" cx="50" cy="50" r="40"></circle>
</svg>
</div>
<input type="number" id="percentageInput" placeholder="输入百分比(0-100)">
<button onclick="updateProgress()">更新进度</button>
<script>
function updateProgress() {
const percentageInput = document.getElementById('percentageInput');
const percentage = parseInt(percentageInput.value, 10);
/*--1. 补全代码,当输入的数据不是数字,或者超出【0,100】,当前函数返回null-----*/
if(typeof percentage !=="number"||percentage<0||percentage>100){
return null
}
const progressRing = document.querySelector('.progress-ring');
const progressCircle = progressRing.querySelector('.progress');
/*--2. 补全代码,计算圆周长-*/
const circumference = 2 * Math.PI * 40;
/*--3. 补全代码,根据输入的百分比设置圆环样式-----*/
const offset = percentage/100*circumference
progressCircle.style.strokeDasharray = `${offset} ${circumference}`;
}
</script>
</body>
</html>
可简单知道:
strokeDasharray ,可以传两个值=》第一个值是:实线占比,第二值是虚线占比。