【问题标题】:jQuery $("body").height() returns undefinedjQuery $("body").height() 返回未定义
【发布时间】:2012-06-13 20:58:13
【问题描述】:

我有这样的电话:

$("#ContextMenuModal").height($("body").height());

但是,当我在 Firebug 中查看 $("body").height() 时,它返回 undefined。

什么会导致 jQuery 返回未定义的身体高度?

我使用的是 jQuery 1.4.1。

编辑:

这是在 iFrame 中

【问题讨论】:

  • 在没有看到测试用例的情况下,我们只能对可能导致这种情况的原因进行疯狂的假设。请创建演示或显示页面。这是demo that shows it working。轮到你了。
  • @bažmegakapa 这是一个我无法发布的大型应用程序,我可以尝试创建一个 repro,但是,我想知道是否存在 jquery 无法确定高度的情况。
  • 当您看不到代码和程序正在运行时,总是很难(几乎不可能?)找到错误。
  • 你是在页面加载后运行这个吗?

标签: javascript jquery


【解决方案1】:

简单使用

$(document).height() // - $('body').offset().top

和/或

$(window).height()

而不是 $('body').height()

稍微扩展一下,

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

正如 bažmegakapa 指出的那样,虽然有几个像素,但还是有细微差别。正文的真实高度可以通过从文档高度减去正文偏移量来计算(就像我上面提到的那样):

$(document).height() - $('body').offset().top

【讨论】:

  • -1 用于显示功能而不提供解释/描述。这两个(嗯,三个)之间有很大的不同。
  • $(window).height() 和 $(document).height() 也都为我返回 undefined
  • @Norse 几个像素,是的。文档可以远高于视口。如果你设置body { margin-top: 2000px; },我会说文档会比正文大得多:)。 A previous question about this.
【解决方案2】:

使用这个-

 $("body").css("height")

我会说不需要 jquery-

this.style.height;//it will not work if you add it as inline js.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 2013-04-22
    • 2021-09-06
    • 2016-12-01
    • 2010-11-29
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多