jquery 进度条计算秒数并在点击时停止

jquery progress bar to count seconds and stop on click

我已经检查了互联网上的很多进度条,但 none 似乎可以处理以下情况:

  1. 显示一个进度条,该进度条会在后台根据时间自动更新。例如简单来说,jqueryUI 进度条会每秒在后台自动更新一次,直到 5 秒(在 5 秒时它处于 100% 并停止)。

  2. 点击某处停止它的可能性。

此用例是在显示进度的简单儿童游戏中,但当任务完成时,有一种简单的方法可以停止进度条。

在 jquery/javascript 中有实现此功能的简单方法吗?

Edit,根据 DavidKonrad 接受的答案,我创建了一个小型打字稿 class,并额外支持 _gProgressAlive 以查询进度是否为 运行 ,以及在进度完成时采取行动的回调。这是结果,希望对其他人有帮助!

var  _gProgressStatus=0;
var _gProgressMax=3;
var _gProgressIncrement=1000;
var _gProgress;
var _gProgressAlive=false;
class ProgressBar{

static stop() {
  clearInterval(_gProgress);
  _gProgressAlive=false;

}

static start(endCallback){
    _gProgressAlive=true;
     _gProgressStatus=0;
  _gProgress = setInterval(function() {
  _gProgressStatus++; 
  $("#progressbar").progressbar({
   value :_gProgressStatus,max:_gProgressMax
  });
  if (_gProgressStatus >=  _gProgressMax){ ProgressBar.stop();endCallback();}
}, _gProgressIncrement);
}

}

这是主要的 html 测试标记

<script>
ProgressBar.start(function(){   
    console.log("completed, time's up");
    console.log(_gProgressAlive); // false progress is complete, this is the callback
});
    console.log(_gProgressAlive); // should output true, progress bar has started
  </script>
<div id="progressbar"></div>

嗯,是的 - 它很容易实现。如果您提供了一个标记示例以及到目前为止您尝试过的内容,事情会更容易:)

标记:

<div id="progressbar"></div>

脚本:

$("#progressbar").progressbar({
  value: 0,
  max : 5  
});

var value = 0,
    progress;

function stopProgress() {
  clearInterval(progress);
  $("#progressbar").progressbar({
     value : 0
  });
}

progress = setInterval(function() {
  value++; 
  $("#progressbar").progressbar({
    value : value
  });
  if (value == 5) clearInterval(progress);
}, 1000);

$(window).on('click', function() {
   stopProgress();
});    

jQueryUI 演示 -> http://jsfiddle.net/vqadbkj9/

停止进度条表示任务已完成。因此,它应该在停止时显示填充状态。我假设这就是你的意思。这是代码:

HTML:

<body onload="expand()">
    <div id="parent">
        <div id="child"></div>
    </div>
    <button onclick="stop()">Stop</button>
</body>

CSS:

#parent
{
    width:100px;
    height:10px;
    background-color:rgb(100,100,100);
}

#child
{
    float:left;
    width:0px;
    height:10px;
    background-color:red;
    transition: all 5s linear;
}

JavaScript:

function expand()
{
    document.getElementById("child").style.width = "100px";
}

function stop()
{
    document.getElementById("parent").style.backgroundColor = "red";
}