我需要设置什么限制值才能停止我的功能?

我正在尝试仅使用Javascript创建一个带有百分比文本的进度条,但我不知道我需要在函数中设置什么值来限制增量。栏和文本不断增加。需要创建4个技能栏,分别为30%/ 50% / 70%和90%。


请帮忙!接受任何建议!这是我的代码。


    <div class="progress">

        <div class="progress-bar"></div>

        <p value="30" class="text">30</p>

    </div>


  <script>

    function update() { 

      let element = document.querySelector(".progress-bar");    

      let counter = document.querySelector(".text");

      var width = 1; 

      var identity = setInterval(scene, 10); 

      function scene() { 

        if (width >= counter.value) { 

          clearInterval(identity); 

        } else { 

          width++;  

          element.style.width = width + '%';  

          counter.innerHTML = width * 1  + '%'; 

        } 

      } 

    } 

</script>


富国沪深
浏览 74回答 2
2回答

慕无忌1623718

欢迎来到Stackoverflow!您可以在下面看到代码的工作示例,只需进行最少的更改。我刚刚定义,当百分比达到100时,它会清除页面上的间隔。function update() {&nbsp; let element = document.querySelector(".progress-bar");&nbsp; let counter = document.querySelector(".text");&nbsp; var percenteage = 0;&nbsp; var identity = setInterval(scene, 50);&nbsp; function scene() {&nbsp; &nbsp; if (percenteage < 100) {&nbsp; &nbsp; &nbsp; percenteage++;&nbsp; &nbsp; &nbsp; element.style.width = percenteage + '%';&nbsp; &nbsp; &nbsp; counter.innerHTML = percenteage + ' %';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; clearInterval(identity);&nbsp; &nbsp; &nbsp; console.log("Cleared!");&nbsp; &nbsp; }&nbsp; }}update();.progress-bar {&nbsp; height: 10px;&nbsp; background-color: red;}<div class="progress">&nbsp; <div class="progress-bar"></div>&nbsp; <p value="30" class="text">30</p></div>

RISEBY

我不确定我是否正在跟踪您遇到的问题。我看到你的代码可以改进,并会解决一些问题。以下是我的建议:function update() {&nbsp;&nbsp; let element = document.querySelector(".progress-bar");&nbsp; &nbsp;&nbsp;&nbsp; let counter = document.querySelector(".text");&nbsp; let width = 1;&nbsp;&nbsp; setTimeout(scene, 1);&nbsp;&nbsp; function scene() {&nbsp;&nbsp; &nbsp; if (width < 100) {&nbsp; &nbsp; &nbsp; width++;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; element.style.width = width + '%';&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; counter.innerHTML = width * 1&nbsp; + '%';&nbsp;&nbsp; &nbsp; &nbsp; setTimeout(scene, 1);&nbsp;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; //Complete action here&nbsp; &nbsp; }&nbsp;&nbsp; }&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript