仅使用JavaScript的Javascript Progressbar动画

时间:2015-05-07 18:39:12

标签: javascript html

我需要用JavaScript创建动画。我不能使用CSS3。当加载页面时,进度条的宽度应增加到给定参数x

我在实施它时遇到了麻烦。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
    #progressbar 
    {
      background-color: black;
      border-radius: 13px; 
      padding: 3px;
      width:100%;
    }
    #progressbar2  
    {
       background-color: orange;
       width: 15%;
       height: 20px;
       border-radius: 10px;
       text-align: center;
       position: relative;
    }

    </style>
    <script>
     function func(x)
     {      
            var result = x;
            document.getElementById("progressbar2").style.width=result+"%";
            document.getElementById("progressbar2").innerHTML=result +"%";      
     }
    </script>
</head>
<body onload="func(50);">
    <div id="progressbar">
        <div id="progressbar2"></div>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您可以使用requestAnimationFrame()来完成您要找的内容。你可以将它全部包含在一个函数中,如下所示:

// Move the progress bar to the given `n` over `overMs` ms. 
function progressBarTo(id, n, overMs) {
  function progressToStep(x) {
    var result = x;
    document.getElementById(id).style.width = result + "%";
    document.getElementById(id).innerHTML = result.toFixed(2) + "%";
  }

  var start;

  function animateBar(timestamp) {
    if (!start) start = timestamp;

    var progress = timestamp - start;
    progressToStep((progress / overMs) * n);
    if (progress < overMs) {
      requestAnimationFrame(animateBar);
    } else {
      progressToStep(n);
    }
  }

  requestAnimationFrame(animateBar);
}

progressBarTo("bar1", 20, 5000);
progressBarTo("bar2", 40, 2500);
progressBarTo("bar3", 60, 1500);
progressBarTo("bar4", 80, 750);
.outer-bar {
  background-color: black;
  border-radius: 13px;
  padding: 3px;
  width: 100%;
}
.inner-bar {
  background-color: orange;
  width: 0%;
  height: 20px;
  border-radius: 10px;
  text-align: center;
  position: relative;
}
<div class="outer-bar">
  <div id="bar1" class="inner-bar"></div>
</div>
<div class="outer-bar">
  <div id="bar2" class="inner-bar"></div>
</div>
<div class="outer-bar">
  <div id="bar3" class="inner-bar"></div>
</div>
<div class="outer-bar">
  <div id="bar4" class="inner-bar"></div>
</div>