<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS实现进度条功能</title>
<style>
#header {
width: 400px;
height: 50px;
border: 3px solid red;
}
#inner {
width: 0px;
height: 50px;
background-color: lightgreen;
font-size: 30px;
text-align: center;
}
#button {
width: 70px;
height: 40px;
margin-top: 30px;
}
</style>
</head>
<body>
<div id="header">
<div id="inner">
<span id="texter"></span>
<span>%</span>
</div>
</div>
<button id="button">加载</button>
<script>
let button = document.getElementById('button');
let inner = document.getElementById('inner');
let texter = document.getElementById('texter');
let timer = null;
button.onclick = function () {
let width_values = 0;
if (timer == null) {
timer = setInterval(() => {
width_values += 80;
inner.style.width = width_values + 'px';
texter.innerText = Math.ceil(width_values / 400 * 100);
if (width_values >= 400) {
clearInterval(timer);
}
}, 1000);
}
}
</script>
</body>
</html>