使用animate() JQUERY获取进度

get the progress with animate() JQUERY

本文关键字:获取 JQUERY animate 使用      更新时间:2023-09-26

这是spinet:

$('#processing .progress-bar').animate({'width':'60%'},4000);

是否有可能显示毫秒是如何倒计时的功能?

例如,我希望能够显示:

4000
3000
2000
1000
0000

则函数停止

您可以在jquery动画中添加一个step函数,并在其中计算动画完成的剩余时间:

$(function () {
    var Now = 0;
    var animationDuration = 4000;
    var DesiredWidth = "200";
    $(".test").animate({
        width: DesiredWidth
    }, {
        easing:"linear",
        duration: animationDuration,
        //the argument in the step call back function will hold the
        // current position of the animated property - width in this case.
        step: function (currentWidth,fx) {
            Now = Math.round((100/DesiredWidth)*currentWidth);
            $(".ms_span").text(Now+"%");
        }
    });
});
div {
  width: 0;
  height: 100px;
  display: block;
  background: purple;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
<br/>Percent: <span class="ms_span">

var duration = 4000,
    interval = 1000,
    pbar = $('#processing .progress-bar');
pbar.text( duration );
var cd = setInterval(function() {
  duration -= interval;
  pbar.text( duration );
}, interval);
pbar.animate({'width':'60%'}, duration, function() {
  clearInterval(cd);
  pbar.text( '0000' );
});
.progress-bar {
  background-color: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="processing">
  <div class="progress-bar">pBar</div>
</div>

看了@Banana的解决方案后,我意识到我完全忘记了step函数和新的(ish) progress函数,它们都可以传递给.animate。我更新的解决方案如下,我已经删除了另一个,以避免混淆。

var $steps = $("#steps");
$('#processing .progress-bar').animate({
  'width': '60%'
}, {
  duration: 4000,
  progress: function(prom, prog, rem) {
    $steps.html("Prog: " + prog + "<br/>Rem: " + rem);
  }
});
#processing {
  width: 80%;
  margin: 5%;
  border: 2px solid black;
  height: 25px;
}
#processing .progress-bar {
  height: 100%;
  background: lime;
  width: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div id="processing">
    <div class="progress-bar"></div> <span id="steps"></span>
  </div>
</div>

作为旁注,根据您计划使用它的目的,您可能想要研究的另一件事是jQuery的.progress方法,它处理进度通知。请注意,我很确定在动画本身上调用.progress不会有任何效果,除非你使用上面的解决方案来在动画的每一步制作进度通知。这是通过调用.notify.notifyWith来完成的,但在动画中这样做有点极端。无论如何,这对于异步调用运行时间不确定的情况非常有用。

  • Docs for deferred.promise .
  • Docs for deferred.notify .
  • Docs for deferred.notifyWith .