效果如下:
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 400px;
border: 1px solid #cd2525;
margin-bottom: 30px;
}
.process {
width: 0px;
height: 40px;
background-color: #f0f;
text-align: center;
line-height: 40px;
}
</style>
</head>
<body>
<div class="box">
<div class="process">
<span>0</span><span>%</span>
</div>
</div>
<button>安装</button>
<script>
var btn = document.querySelector('button');
var box = document.querySelector('.box');
var process = box.querySelector('.process');
var span = process.querySelector('span');
let timer = null;
btn.addEventListener('click', function () {
let width = 0;
if (timer == null) {
timer = setInterval(function () {
if (width == 400) {
clearInterval(timer);
} else {
width += 4;
process.style.width = width + 'px';
span.innerHTML = parseInt(width * 100 / 400);
}
}, 100);
}
})
</script>
</body>
</html>