【发布时间】:2018-02-25 05:14:14
【问题描述】:
我有一个带有 JS 动画的简单进度条。每 20 毫秒,进度条的值增加 0.25。因此完成进度条需要 20*4*100ms = 8 秒,如下面的 JSFiddle 所示。
function updateProgress(currentValue, expectedValue){
var inProgress = setInterval(function() {
currentValue = currentValue + 0.25;
$('#progress-bar').attr('value', currentValue);
$('#progress-text').text(Math.round(currentValue));
if (currentValue == expectedValue) clearInterval(inProgress);
}, 20);
}
updateProgress(0, 100);
<progress id="progress-bar" value="0" max="100"></progress>
<div><span id="progress-text">0</span>%</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
因此,如果我采用相同的代码并以 50% 而不是 0% 启动进度条,则完成进度条需要 20*4*50ms = 4 秒,如下面的 JSFiddle 所示。
function updateProgress(currentValue, expectedValue){
var inProgress = setInterval(function() {
currentValue = currentValue + 0.25;
$('#progress-bar').attr('value', currentValue);
$('#progress-text').text(Math.round(currentValue));
if (currentValue == expectedValue) clearInterval(inProgress);
}, 20);
}
updateProgress(50, 100);
<progress id="progress-bar" value="50" max="100"></progress>
<div><span id="progress-text">50</span>%</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
我希望该函数始终具有相同的执行时间,而无需考虑起始值。 例如 0 到 -> 100 :4 秒,50 到 -> 100 也是 4 秒。
我试过了,但它不起作用:
function updateProgress(currentValue, expectedValue){
var interval = 4000 / (expectedValue - currentValue) / 4;
var inProgress = setInterval(function() {
currentValue = currentValue + 0.25;
$('#progress-bar').attr('value', currentValue);
$('#progress-text').text(Math.round(currentValue));
if (currentValue == expectedValue) clearInterval(inProgress);
}, interval);
}
updateProgress(50, 100);
【问题讨论】:
标签: javascript jquery html setinterval