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

jquery progress bar to count seconds and stop on click

本文关键字:单击 jquery      更新时间:2023-09-26

我在互联网上查看了很多进度条,但似乎没有一个能处理以下情况:

  1. 显示一个进度条,它会随着时间的推移在后台自动更新。例如,简单地说,jqueryUI进度条将每秒在后台自动更新一次,直到5秒(在5s时,它处于100%并停止)。

  2. 点击某个地方停止它的可能性。

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

有没有一种简单的方法可以在jquery/javascript中实现这一点?

编辑,根据DavidKonrad接受的答案,我创建了一个小型的typescript类,并额外支持_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";
}