jQuery: .height() returns null in .ready() 但它在 运行 相同的代码控制台时有效

jQuery: .height() returns null in .ready() but it works when run the same code console

我正在尝试将高度分配给主 div 容器,以便仅将滚动条提供给这个“rightContent”div。

我所做的就是找出所有其他 DIV 的高度,然后减去那些具有“window”高度的 DIV 的高度,得到主 div 的高度” rightContent"

但我遇到了一个问题,我得到了除“.tabstripContainer”之外所有 "DIVs" 的高度 div,它是动态的 DIV,它在运行时间生成。

我在“.ready()”页面末尾添加了以下代码,但是当我 运行 代码时,它的 returns "null" 对于“tabstripContainer = $('.tabstripContainer').outerHeight();

这是我 运行 代码时的输出:

============================================= ==============

但是 当我 运行 浏览器控制台中的代码时,我得到了正确的值 "tabstripContainer = $('.tabstripContainer').outerHeight();”还有。”

这是我在浏览器控制台中 运行 我的代码时的输出:

============================================= ======================= 这是我的代码:

$(document).ready(function() {
    // -----------------------------------------------------
    // 100% height fill for splitter main window and panes [Master layout]
    // -----------------------------------------------------
    var bHeight = $('body').height(),
        wHeight = $(window).height(),
        headerHeight = $('header').outerHeight(),
        blueHeader = $('.blueHeader').outerHeight(),
        greyHeader = $('.greyHeader').outerHeight(),
        tabstripContainer = $('.tabstripContainer').outerHeight();

    changepush();
    $(window).resize(function() {
        wHeight = $(window).height();
        changepush();
    });

    function changepush() {
        if (wHeight >= bHeight) {
            var rightContent = wHeight - headerHeight - blueHeader - greyHeader - tabstripContainer;
            $('.rightContent').height(rightContent);

            alert("bHeight" + " > " + bHeight + " wHeight" + " > " + wHeight + " headerHeight" + " > " + headerHeight + " blueHeader" + " > " + blueHeader + " greyHeader" + " > " + greyHeader + " tabstripContainer" + " > " + tabstripContainer + " rightContent" + " > " + rightContent);
        }
    }
});

求推荐!

我没有足够的声誉来发表评论,所以不得不提供这个作为答案。

您是否尝试过使用 $(window).load 而不是 $(document).ready?前者在加载其他页面资产(例如图像)时触发,而后者将在 DOM 准备就绪时触发。

如果您在运行时创建内容,则需要等到发生这种情况。 document.ready 在浏览器完成解析所有 DOM 之后立即触发,但 其他脚本(如 ajax 调用等)之前触发。

一个可能的解决方案是延迟 change push() 使用 setTimeout 调用,或者在您的内容显示后调用该函数。

另一个解决方案是在您的 div 内容加载后触发您自己的事件(即 "contentLoaded")。

您可以尝试使用 window.load 而不是 document.ready,在完成所有外部请求(imgs、帧等)后触发的事件。

setTimeout 参考:https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

jQuery 自定义事件:https://learn.jquery.com/events/introduction-to-custom-events/