我想创建一个loadingbar/progressbar,它随着值(var(的增加而加载。我不知道该怎么办。我有工具。例如,从我的Firebase DB中提取的动态切换值,该值基于某个动作而递增。然而,我不确定如何创建这个进度条,以及如何根据动态递增值加载它。
有什么建议吗?
您可以使用以下内容:
function increaseWidth(percent) {
let containerWidth = document.getElementById('progressBarContainer').clientWidth; // get the container width
let amount = Math.round(containerWidth * percent/100); // get amount of pixels the bars width needs to increase
let barWidth = document.getElementById('bar').offsetWidth; // get the current bar width
// if the bar width + amount of pixels to increase exceeds the container's width, reduce it accordingly
if(barWidth + amount > containerWidth) {
amount = containerWidth - barWidth;
clearInterval(bar); // we reached 100% so clear the interval
}
let totalPercent = Math.round((barWidth + amount) * 100/ containerWidth); // calculate the total percent finished
document.getElementById('bar').style.width = barWidth + amount + "px"; // increase bar width
document.getElementById('text').innerHTML = totalPercent + "%"; // update the percentage text
}
// this is just to mimic generating "work done" percentage
var bar = setInterval(function() {
let percentage = Math.floor(Math.random() * 10 + 1); // generate a percentage of work done
increaseWidth(percentage);
}, 1000)
#progressBarContainer {
position: relative;
float:left;
width: 200px;
height: 20px;
border: 1px solid #09f;
background-color: #000;
}
#bar {
position: relative;
float:left;
width: 0;
height: 20px;
background-color: #f00;
}
#text {
position: absolute;
height: 20px;
width: 200px;
top: 0px;
left: 0px;
color: #fff;
text-align:center;
line-height:20px;
}
<div id="progressBarContainer">
<div id="bar">
<div id="text"></div>
</div>
</div>
如果您不介意使用JQuery,请尝试使用JQuery UI Progressbar Widget。您必须首先使用标题中的<script>
标签将JQUERY UI库添加到您的网站:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha256-KM512VNnjElC30ehFwehXjx1YCHPiQkOPmqnrWtpccM=" crossorigin="anonymous"></script>
然后用最大值初始化进度条;如果你想使用百分比,那应该是100。
$("#progressbarElementID").progressbar({
max: 100
});
然后通过写入百分比进行更新:
$("#progressbarElementID").progressbar({
value: 74 // Or whatever percent you want...
});
根据需要重复更新功能以更改进度条。
有关更深入的教程,您可以参考API文档了解此功能。