要将进度条的值添加到进度条元素的中心,可以使用HTML、CSS和JavaScript来实现。以下是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Progress Bar with Value</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="progress-bar">
<div class="progress" id="progress"></div>
<div class="progress-value" id="progressValue">0%</div>
</div>
<button onclick="updateProgress()">Update Progress</button>
<script src="script.js"></script>
</body>
</html>
.progress-bar {
width: 100%;
height: 30px;
background-color: #f3f3f3;
border-radius: 5px;
position: relative;
}
.progress {
height: 100%;
width: 0%;
background-color: #4caf50;
border-radius: 5px;
}
.progress-value {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-weight: bold;
}
function updateProgress() {
const progress = document.getElementById('progress');
const progressValue = document.getElementById('progressValue');
let width = 0;
const interval = setInterval(() => {
if (width >= 100) {
clearInterval(interval);
} else {
width++;
progress.style.width = width + '%';
progressValue.textContent = width + '%';
}
}, 50);
}
<div>
元素来表示进度条和进度值。updateProgress
来更新进度条的宽度和显示的值。setInterval
来模拟进度的逐步增加。.progress-value
的position
属性设置为absolute
,并且使用transform: translate(-50%, -50%)
来精确居中。width
变量正确更新,并且及时应用到.progress
元素的style.width
属性上。通过这种方式,你可以创建一个带有中心显示值的进度条,并且可以根据需要进行扩展和定制。
领取专属 10元无门槛券
手把手带您无忧上云