【问题标题】:jQuery outerHeight is not returning the correct valuejQuery outerHeight 没有返回正确的值
【发布时间】:2013-06-23 15:04:14
【问题描述】:

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

每个函数参数都接受一个元素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 值返回了错误的值。页眉返回 23 像素,页脚返回 40 像素。

检查 FF 和 Chrome 中的元素时,值是 25px 和 44px。

我尝试过使用 innerHeight、outerHeight 和 outerHeight(true),但没有得到正确的值。

对可能出现的问题有什么建议吗?还是动态设置内容高度的替代方法?我的头发快用完了,所以感谢您的帮助。

编辑:我正在处理 iframe 中的内容。以下内容:winH = top.innerHeight 正在获取最顶部 iframe 窗口的高度值。

【问题讨论】:

  • 什么是top?它持有什么?请也显示您的布局。
  • 我有在 iframe 中弹出的自定义窗口; top 正在获取最高 iframe 高度。

标签: javascript jquery html dynamic


【解决方案1】:

尝试对我有帮助的一件事是将检查outerHeight() 的代码放入$(window).load() 而不是$(document).ready()。显然在很多情况下使用$(document.ready() 是可以的,但有时outerHeight() 的值不正确是由于元素没有完全加载造成的。

【讨论】:

  • 我应该补充一点,(window).load() 在页面上的所有元素(包括图像)完成加载后调用。
  • 你好@Gaving,你能帮我看看我应该如何使用 $(window).load() 和 outerHeight() 吗?我是 JS 新手,不知道代码会有什么相似之处。
【解决方案2】:

我修改了用于计算屏幕宽度/高度的脚本。看看这是否有效:

    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";

【讨论】:

  • 我修改了您的脚本以使用我当前的代码,但它返回的值与我的原始代码相同。
  • 页眉和页脚是动态的吗?如果不是,您可以将 .outerHeight(true) 替换为其高度的像素数量。
  • 这是我目前的工作,但我需要代码尽可能动态。因此,我需要能够获取这些值。
  • 我明白了,我会深入研究的。
  • 这个问题似乎是 Firefox 特有的。显然页眉和页脚的高度是 23px 和 40px,而在 Firefox 中它们是 25px 和 44px。这让我相信这是浏览器如何显示内容的问题。
猜你喜欢
  • 2015-08-20
  • 2014-11-26
  • 2013-06-21
  • 2019-03-21
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多