使用动态增量值创建加载栏

create a loading bar using an dynamic incrementing value

我想创建一个随着值 (var) 增加而加载的加载条/进度条。我不知道如何绕过 this.I 拥有工具。例如从我的 Firebase 数据库中提取的动态变化值,该值会根据特定操作递增。但是我不确定如何创建这个进度条以及如何根据动态增量值加载它。

有什么建议吗?

您可以使用如下内容:

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。您必须首先使用 header:

中的 <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...
});

根据需要重复更新功能以更改进度条。

更多in-depth教程可以参考API docs for this feature.