0

我刚刚开始我的旅程,javascript我正在努力寻找解决问题的方法。

我创建了一个 div,它是一个进度条,当我们按下按钮时,它会逐渐填满 div 的整个宽度。按钮的默认宽度应该从 0% 开始到 100%。我正在尝试提出jQuery或香草javascript,但我无法做到这一点。任何帮助都会很棒,因为我真的对提高我的jQuery/JS技能很感兴趣。

<div id="myProgress">
    <div id="progressbar"></div>
    <button id="button-progress"></button>
</div>
#myProgress {
    width: 100%;
    background-color: #ddd;
}

#progressbar {
    width: 0%;
    height: 30px;
    background-color: #1D1387;
    text-align: center;
    line-height: 30px;
    color: white;
}
4

2 回答 2

0

你可以这样做:

var i = 0;
function move() {
  if (i == 0) {
    i = 1;
    var elem = document.getElementById("myBar"); //get element
    var width = 10; //Set value
    var id = setInterval(frame, 10); // set the time interval
    function frame() {
      if (width >= 100) {
        clearInterval(id); //If width is already 100% clear interval
        i = 0;//reset to counter
      } else {
        width++;
        elem.style.width = width + "%"; //Update the style
        elem.innerHTML = width  + "%"; //Update the counter
      }
    }
  }
}
<style>
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 10%;
  height: 30px;
  background-color: #4CAF50;
  text-align: center;
  line-height: 30px;
  color: white;
}
<div id="myProgress">
  <div id="myBar">10%</div>
</div>

<br>
<button onclick="move()">Click Me</button> 

于 2019-11-16T10:31:08.180 回答
0

您可以使用 jQuery 动画功能。使用 step 选项将给出动画的当前进度。用它来更新计数器。此外,您可以使用持续时间选项控制持续时间。

jQuery("#button-progress").on("click", function() {
  jQuery("#progressbar").animate({
    width: "100%"
  }, {
    // The entire duration of the animation
    duration: 2000,
    // Runs every step of the animation
    step: function(number) {
      let current = Math.floor(number);
      jQuery(this).text(current + "%");
    }
  });
});
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#progressbar {
  width: 0%;
  height: 30px;
  background-color: #1D1387;
  text-align: center;
  line-height: 30px;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myProgress">
  <div id="progressbar">0%</div>
</div>
<br><br>
<button id="button-progress">Animate !</button>

于 2019-11-16T13:09:36.100 回答