使用Javascript模拟进度条

时间:2017-08-21 12:08:13

标签: javascript jquery html css

我想增加progessbar的值。达到最大值时应该停止。此代码应模拟服务器调用,用户必须等待并且应禁用输入。

function serverCall() {
    var container = $("#disabledBackgroundContainer"),
        progressBar = $("#progressBar"),
        duration = 5000,
        currentProgess = 0,
        steps = 1;

    progressBar.prop("max", duration);
    container.css("display", "block");

    currentProgess = setInterval(function () {
        currentProgess += steps;
        progressBar.val(currentProgess);

        if (currentProgess >= duration) {
            clearInterval(currentProgess);
            container.css("display", "none");
        }
    }, steps);
}
#disabledBackgroundContainer {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    position: absolute;
    background-color: #333333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn btnDark" onclick="serverCall()">Server Call</button>
        <div id="disabledBackgroundContainer">
            <progress id="progressBar"></progress>
        </div>

正如你所看到的,progessbar永远不会停止,似乎我的代码中有一个循环。但我没有得到正确的方法来解决这个问题。

1 个答案:

答案 0 :(得分:2)

您正在使用 String value = currencySymbol+" /Monat"; numberFormat = NumberFormat.getFormat(value); 进行两项不同的事情:计时器ID和要检查的增量编号。

您需要使用两个不同的变量:

currentProgess

其次,从HTML var timer = setInterval(function () { currentProgess += steps; progressBar.val(currentProgess); if (currentProgess >= duration) { clearInterval(timer); container.css("display", "none"); } }, steps); 属性中删除哈希。应该是id。哈希只有作为CSS选择器的含义(在您的代码和样式部分中):

&#13;
&#13;
id="progressBar"
&#13;
function serverCall() {
    var container = $("#disabledBackgroundContainer"),
        progressBar = $("#progressBar"),
        duration = 5000,
        currentProgess = 0,
        steps = 1;

    progressBar.attr("max", duration);
    progressBar.attr("value", 2000);
    container.css("display", "block");

    var timer = setInterval(function () {
        currentProgess += steps;
        progressBar.attr('value', currentProgess);

        if (currentProgess >= duration) {
            clearInterval(timer);
            container.css("display", "none");
        }
    }, steps);
}
&#13;
#disabledBackgroundContainer {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    position: absolute;
    background-color: #333333;
}
&#13;
&#13;
&#13;