【问题标题】:Javascript progress bar not showing correct percentage of completionJavascript进度条未显示正确的完成百分比
【发布时间】:2020-09-26 09:12:16
【问题描述】:

在下面的代码中,我试图让进度条显示 100%,但它保持在 66%。这是一个包含三个问题的测验。在提交第三个问题后,第一个问题和第二个问题分别显示 33% 和 66% 时,它仍然显示 66%,但条形完全完成跨越条形的整个宽度。完成代码笔here.。第三个问题后如何显示100%?谢谢。

进度条JS代码:

function move(i) {
    console.log('i: ' + i);
    var elem = document.getElementById("myBar");
    switch(i) {
      case 0:
        elem.style.width = "33%";
        elem.innerHTML = "33%";
        break;
      case 1:
        elem.style.width = "66%";
        elem.innerHTML = "66%";
        break;
      case 2:
        elem.style.width = "100%";
        elem.innerHTMl = "100%";
    }
  }

【问题讨论】:

  • innerHTML in case 2 not innerHTMl - 你的其余代码工作正常

标签: javascript


【解决方案1】:

你一定要试试这个

<style>
#myProgress {
    width: 100%;
    background-color: grey;
}
#myBar {
    width: 1%;
    height: 30px;
    background-color: green;
    text-align:center;color:white;
}
</style>
<p id="count">1%</p>
<div id="myProgress">
  <div id="myBar"></div>
</div>

<button onclick="move(10)">10%</button> 
<button onclick="move(33)">33%</button> 
<button onclick="move(66)">66%</button> 
<button onclick="move(100)">100%</button> 

<script>
function move(x) {
    var elem = document.getElementById("myBar");
    var count = document.getElementById("count");
    var width = 1;
    var id = setInterval(frame, 1);
    function frame() {
        if (width >= x) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            count.innerHTML = width + '%';
        }
    }
} 
</script>

【讨论】:

  • You must try this 的任何具体原因?有什么改变并且比 OP 现有的代码更好?
  • 我确定这是“正确”和“完整”的代码。我不仅在考虑这个特殊案例,我希望这对未来的其他用户有所帮助。
【解决方案2】:

我有一个更通用的方法来做到这一点,因为 myQuestions 变量可以有任何长度,所以使用 switch case 不适合这样做。

function move(slide, total) {
  console.log('slide: ' + slide);
  var elem = document.getElementById("myBar");
  const percent = (slide + 1) / total * 100;
  elem.style.width = `${percent}%`;
  elem.innerHTML = percent != 100 ? `${percent.toPrecision(2)}` : "100%";
}

// From your code you can just call like this
move(currentSlide, myQuestions.length);

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2017-05-12
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多