jQuery的outerHeight未返回正确的值

8

我正在尝试通过从窗口大小中减去页眉和页脚的值,并在文档加载时将内容设置为此值,动态设置网页内容的高度。

每个函数参数都接受一个元素id,以便获取元素高度;不包括内容参数。

 function setH(header, content, footer) 
{
    winH = top.innerHeight;
    winTitle = 32; // height value of the window title (part of the header)
    headH = $(header).outerHeight(true);
    footH = $(footer).outerHeight(true);
    contentH = winH - winTitle - headH - footH;
    $(content).css({'height' : (contentH) + 'px','overflow-y' : 'scroll'});
}

我遇到的问题是outerHeight值返回错误。标题返回23px,页脚返回40px。
在FF和Chrome中检查元素时,这些值分别为25px和44px。
我尝试使用innerHeight、outerHeight和outerHeight(true),但没有得到正确的值。
您有什么建议可能出了什么问题?或者有没有其他动态设置内容高度的替代方法?我已经没有头发可以拔了,所以非常感谢任何帮助。
编辑:我正在处理iframe中的内容。以下代码:winH = top.innerHeight获取最顶层iframe窗口的高度值。

什么是“top”?它保存了什么?请展示你的布局。 - Starx
我有自定义窗口弹出在iframe中;顶部正在获取最顶层的iframe高度。 - seen_my_dog
2个回答

17

有一个我试过的方法可以帮助我解决这个问题,那就是把检查outerHeight()的代码放在$(window).load()而不是$(document).ready()。显然,在许多情况下,使用$(document.ready()是可以的,但有时候outerHeight()的错误值是由于元素没有完全加载而引起的。


1
我应该补充的一件事是,(window).load()在页面上的所有元素,包括图像,都加载完成后才会被调用。 - Gavin
你好 @Gaving, 请问你能帮我解决如何在 $(window).load() 中使用 outerHeight() 吗?我是 JS 的新手,不太确定代码应该怎么写。 - r_e

1

我修改了一个用于计算屏幕宽度/高度的脚本。看看这个是否可行:

    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth;
        viewportheight = window.innerHeight;
        winTitle = 32;
        headH = $(header).outerHeight(true);
        footH = $(footer).outerHeight(true);
        contentH = viewportheight - winTitle - headH - footH;
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
        viewportwidth = document.documentElement.clientWidth;
        viewportheight = document.documentElement.clientHeight;
        winTitle = 32;
        headH = $(header).outerHeight(true);
        footH = $(footer).outerHeight(true);
        contentH = viewportheight - winTitle - headH - footH;
    }

    // older versions of IE

    else {

    viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
    viewportheight = document.getElementsByTagName('body')[0].clientHeight;
    }
    document.getElementById("content id").style.height = contentH + "px";

我修改了你的脚本以适应我的当前代码,但它返回的值与我的原始代码相同。 - seen_my_dog
页眉和页脚是否是动态的?如果不是,您可以用它们的高度像素数替换.outerHeight(true)。 - Jefferson
这是我目前的解决方案,但我需要代码尽可能地动态化。因此,我需要能够获取值。 - seen_my_dog
我明白了,我会深入研究这个问题。 - Jefferson
问题似乎是Firefox特有的。显然,页眉和页脚的高度分别为23px和40px,而在Firefox中它们为25px和44px。这让我相信这是浏览器显示内容的问题。 - seen_my_dog
如果是这种情况,您可能需要添加样式重置以确保浏览器的一致性。http://meyerweb.com/eric/tools/css/reset/ - Jefferson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接