用CSS+SVG做一个优雅的环形进度条
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>环形进度条示例</title>
<style>
.circle-progress {
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
}
.circle-progress .circle-bg {
fill: none;
stroke: #eee;
stroke-width: 5;
}
.circle-progress .circle-progress-bar {
fill: none;
stroke-linecap: round;
stroke-width: 5;
stroke: #3498db;
r: 45;
}
.circle-progress .circle-text {
position: absolute;
text-align: center;
line-height: 1;
font-family: sans-serif;
font-size: 16px;
font-weight: bold;
color: #333;
}
</style>
</head>
<body>
<div class="circle-progress" data-progress="75">
<svg viewBox="0 0 100 100">
<circle class="circle-bg" r="45" cx="50" cy="50"/>
<circle class="circle-progress-bar" r="45" cx="50" cy="50"
stroke-dasharray="282.74" stroke-dashoffset="213.74"/>
</svg>
<div class="circle-text">75%</div>
</div>
<script>
const circleProgress = document.querySelector('.circle-progress');
const progressBar = circleProgress.querySelector('.circle-progress-bar');
const progress = parseInt(circleProgress.dataset.progress, 10);
const circumference = progressBar.r.baseVal.value * 2 * Math.PI;
progressBar.style.strokeDashoffset = `${circumference - (progress / 100 * circumference)}`;
</script>
</body>
</html>
这段代码展示了如何使用SVG和CSS创建一个简洁的环形进度条。.circle-progress
是容器,.circle-bg
是进度条的背景环,.circle-progress-bar
是进度条本身,.circle-text
是显示进度百分比的文本。通过JavaScript动态计算进度条的stroke-dashoffset
属性,实现进度条的绘制。
评论已关闭