我要使两个进度条在负载下工作。但是我编写的代码仅加载一次。另外,这两个进度条在加载时必须具有不同的长度。我不想重复代码,所以我要添加数组。但是我不太确定这是最好的解决方案。也许在body标签中可以编写两个不同的函数,或者只能加载一个?如果有几个函数可以加载,则不应使用数字数组。我的代码如下。也许有人知道解决方案?
<style>
.myProgress {
width: 100%;
background-color: #000000;
}
#myBar1, #myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body onload="move()">
<div class="myProgress">
<div id="myBar1"></div>
</div>
<div class="myProgress">
<div id="myBar2"></div>
</div>
<script>
function move() {
var ids = ["myBar1", "myBar2"];
var number = [60, 90]
var length = ids.length;
for(i = 1; i<=length; i++){
var elem = document.getElementById("myBar"+i);
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= number[i-1]) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
}
</script>
答案 0 :(得分:0)
引起该问题的原因是,您将循环与异步操作混合在一起,通常情况下效果不佳。如果要执行此操作,则应使用>>> a = [1,2,3]
>>> id(a)
53361720
>>> a += [9]
>>> a
[1, 2, 3, 9]
>>> id(a)
53361720
而不是let
或在其他函数中进行操作。此外,您可以在html元素中设置宽度并阅读所有进度条。
var
function move() {
for (var item of document.querySelectorAll(".myProgress")) {
loading(item.firstElementChild, +item.getAttribute("width") || 100); // replace 100 with default
}
}
function loading(bar, maxWidth) {
var width = 0;
var intervalId = setInterval(function() {
if (width >= maxWidth) clearInterval(intervalId);
else bar.style.width = ++width + '%';
}, 10);
}
.myProgress {
width: 100%;
background-color: #000000;
}
#myBar1,
#myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}