如何用html、css和javascript/angular创建实时进度条



我有一个javascript中的实时进度条,但我需要在多个地方使用它。我只是把它用作装载机。由于我在多个地方使用相同的进度条,我需要它在完成100%后自动返回其原始位置(20%(。这是下面的代码

HTML/JAVASCRIPT

<!DOCTYPE html>
<html>
<body>
<style>
#myProgress {
width: 20rem;
background-color: #ddd;
}

#myBar {
height: 15px;
background-color: #04AA6D;
text-align: center;
line-height: 14px;
color: white;
border-radius: 5px;
font-size: 10px;
}
</style>
<div class="mt-1">Uploading Document....</div>
<div id="myProgress" class="mt-2">
<div id="myBar"></div>
</div>
<div>         
<button onclick="myFunction()">Button1</button>
<button onclick="myFunction2()">Button2</button>
</div>
<script>
function myFunction() {
const elem = document.getElementById('myBar'); 
let width = 20;
const id = setInterval(frame, 40);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++; 
if(elem != null){
elem.style.width = width + '%'; 
elem.innerHTML = width * 1  + '%';
}
}
}
}
function myFunction2() {
const elem = document.getElementById('myBar'); 
let width = 20;
const id = setInterval(frame, 40);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++; 
if(elem != null){
elem.style.width = width + '%'; 
elem.innerHTML = width * 1  + '%';
}
}
}
}
</script>
</body>
</html> 

您可以在if-width中添加一个超时函数>100,然后将所有设置回20%。

function frame() {
if (width == 100) {
clearInterval(id);
setTimeout(()=>{
elem.style.width = "20%"; 
elem.innerHTML = '20%';
}, 500)
} else {
width++; 
if(elem != null){
elem.style.width = width + '%'; 
elem.innerHTML = width * 1  + '%';
}
}
}

最新更新