Jquery $(window).height()函数不返回实际的窗口高度

我有一个页面,当用户滚动到底部时,我需要动态加载ajax内容。 问题是JQuery没有返回正确的窗口高度。 我之前使用过这个函数,从未见过它失败,但由于某种原因,它将返回与文档高度相同的值。 我在这里有测试页面:bangstyle.com/test-images

我已将警报编码为在页面加载时显示,并且每当用户在顶部下方滚动500px时:

function scroller() { if($(window).scrollTop() > 500){ delay(function(){ //200ms wait pagecounter++; sideshow(); alert("window height: " + $(window).height() + " scrolltop: " + $(window).scrollTop() + " document height: " + $(document).height()); return false; }, 200 ); } } 

我之前试过发布这个,但我删除它,因为我没有得到解决方案。 我希望可以发布一个链接到我的测试页面。 顺便说一下,我已经在Mac Safari和Mac FF上测试了这个。 我在其他页面上运行相同的代码,它工作正常。 我觉得这个页面的dom必定会有一些东西导致JS失败,但不知道会是什么。

查看您的HTML源代码。 第一行应该是而你有

标签。

因此,您的文档似乎在Quirks模式下运行,jQuery无法计算正确的窗口尺寸。

 //works in chrome $(window).bind('scroll', function(ev){ //get the viewport height. ie this is the viewable browser window height var clientHeight = document.body.clientHeight, //height of the window/document. $(window).height() and $(document).height() also return this value. windowHeight = $(this).outerHeight(), //current top position of the window scroll. Seems this *only* works when bound inside of a scoll event. scrollY = $(this).scrollTop(); if( windowHeight - clientHeight === scrollY ){ console.log('bottom'); } }); 

我有同样的问题。 我找到了一些东西:

1)当您尝试在文档完成呈现之前获取实际高度时,会发生问题; 2)当您不使用相关DOCTYPE(如上所述)时,谷歌浏览器会出现问题3)即使文档完全呈现后,它也总是发生在谷歌浏览器中。

对于谷歌浏览器,我在这里找到了一个解决方法: get-document-height-cross-browser我正在使用此解决方案仅用于谷歌浏览器 ,它解决了我的问题,我希望帮助那些仍有问题的人。

这是一个老问题,但我最近一直在努力没有在IE10中获得正确的窗口高度几个像素。

我发现默认情况下IE10应用75%的缩放,并拧紧窗口和文档测量值。

因此,如果您的宽度或高度错误,请确保将缩放设置为100%。

有些人环顾四周,偶然发现了这一点,不知道它是否有帮助,但它值得提起。

为什么$(window).height()这么错?

由于jquery(和dom一般)不能在quirksmode中正确计算大小,因此有两种解决方案:

  1. 在页面顶部添加doctype html(如“正确”答案中所述),或
  2. 如果第一个选项不是选项,请使用window.innerHeight,window.innerWidth。

希望能帮助到你。

我将脚本从页脚移动到页脚,并为我解决了这个问题。