javascript - jQuery 等待显示()?得到错误的数据

标签 javascript jquery html css

我正在使用以下代码来计算在 60 秒内减少整个分区的间隔,如果我总是删除 1px:

function startTimer(remainingTime) {
    showProgressBar(true);

    maxWidth = ($('#time').width() - 4);
    progressIntervall = sessionTime / maxWidth * 1000;
    currentProgress = maxWidth * (remainingTime / sessionTime);

    $('#time .progress').width(currentProgress);
    window.setTimeout("decreaseTime()", progressIntervall);

    alert(maxWidth); // = 86
    window.setTimeout("alert($('#time').width());", 100); // = 396
}

function showProgressBar(bol) {
    if (bol) {
        $('#time').show();
        $('#time').removeClass("gray");
    } else 
        $('#time').hide();

}

HTML:

<div id="time" class="gray">
    <div class="progress" style="width: 100%;">&nbsp;</div>
</div>

CSS:

#time
{
    width: 90%;
    max-width: 400px;
}

问题似乎是在 showProgressBar 之后,页面需要一些时间来重新调整元素的大小。例如,ma​​xWidth 是 86 而不是 366。

有什么解决办法吗?

最佳答案

最好将其余效果作为回调传递给 .hide.show,可能像这样:

function startTimer(remainingTime) {
    function restOfAnimation() {
        maxWidth = ($('#time').width() - 4);
        progressIntervall = sessionTime / maxWidth * 1000;
        currentProgress = maxWidth * (remainingTime / sessionTime);

        $('#time .progress').width(currentProgress);
        window.setTimeout("decreaseTime()", progressIntervall);

        alert(maxWidth); // = 86
        window.setTimeout("alert($('#time').width());", 100); // = 396
    }

    showProgressBar(true, restOfAnimation);
}

function showProgressBar(bol, callback) {
    if (bol) {
        $('#time').show(callback);
        $('#time').removeClass("gray");
    } else 
        $('#time').hide(callback);
}

虽然上面的代码需要一些改进(var 没有被使用,这几乎肯定是一个错误;decreaseTimeout 可以直接传递给 setTimeout 等)。

关于javascript - jQuery 等待显示()?得到错误的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12596752/

相关文章:

javascript - 找到 div 中的第一个 img 并在其下方放置一个新 div

javascript - js使用scrollTop,标题边框消失了

html - 在段落内 float block 级元素

javascript - 在 HTML5 中从 sql 检索数据

c# - 为什么 ServerVariables ["HTTP_REFERER"] 跳过一个页面?

javascript - 使用 AJAX 运行实时时钟

javascript - JS中当变量的值是由变量组成的对象时,如何声明变量?

javascript - 为什么我在 node.js 中使用 parseInt 会得到奇怪的结果? (与 chrome js 控制台的结果不同)

javascript - 如何解决vue 3中的错误 "this is undefine"

javascript - 如何从异步调用返回响应?