我的目标网页将针对我所知道的每种技术都有进度百分比。我似乎能想到的唯一解决方案是,为每个函数创建两个具有不同值的函数,然后在body onload中调用它们。这似乎非常混乱。我怎样才能使它更好?
function webMove() {
var elem = document.getElementById("myBar");
var width = 0;
var width2 = 0;
var id = setInterval(frame, 10);
function frame() {
if (width >= 50) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
}
function gitHubMove() {
var elem = document.getElementById("myBar2");
var width = 0;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
}
<body onload="webMove(),gitHubMove()">
<div id="container">
<div id="myProgress">
<div id="myBar">
</div>
</div>
</div>
<div id="container2">
<div id="myProgress2">
<div id="myBar2">
</div>
</div>
</div>
</body>
答案 0 :(得分:1)
只需定义一个对象即可跟踪您想要的内容。这是一个可能的解决方案,可用于所需的多个进度条及其性能,因为仅运行一个时间间隔。我在当前未使用的对象中添加了一个开始,但是如果您想让进度的开始不是0,那就怎么做
function progress() {
keys = ['web', 'github']
var meta = {
web: {
done: false,
current: 0,
max: 50,
start: 0,
elem: document.getElementById("myBar")
},
github: {
done: false,
current: 0,
max: 100,
start: 0,
elem: document.getElementById("myBar2")
}
}
var id = setInterval(frame, 10);
function frame() {
var complete = true
keys.forEach( function(key) {
var obj = meta[key]
if (!obj.done) {
complete = false
}
if (obj.current >= obj.max) {
obj.done = true
return
}
obj.current++
obj.elem.style.width = obj.current + '%';
obj.elem.innerHTML = obj.current * 1 + '%';
})
if (complete) {
clearInterval(id)
}
}
}
progress()
<div id="myBar"></div>
<div id="myBar2"></div>
答案 1 :(得分:0)
您喜欢干码,这是一个很好的习惯。在那里,您对代码做了一些小的修改:
function progressBar(elementId, progressPercent){
var elem = document.getElementById(elementId);
var width = 0;
var id = setInterval(frame, 10);
function frame() {
if (width >= progressPercent) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
}
progressBar("webMove", 80)
progressBar("gitHubMove", 60)
<div id="container">
<div id="myProgress">
<div id="webMove">
</div>
</div>
</div>
<div id="container2">
<div id="myProgress2">
<div id="gitHubMove">
</div>
</div>
</div>