当viewport没有被resize时,jquery $(window).width()和$(window).height()返回不同的值

我正在写一个使用jQuery的网站,反复调用$(window).width()$(window).height()来根据视口大小来定位和调整元素的大小。

在进行故障排除时,我发现当视口未resize时,在重复调用上述jquery函数时,获得的视口大小报告略有不同。

想知道是否有什么特别的情况发生,或者如果是这样的话。 看起来大小的差异是20px或更less。 它发生在Mac OS X 10.6.2上的Safari 4.0.4,Firefox 3.6.2和Chrome 5.0.342.7 beta版本中。 我还没有testing其他浏览器,因为它似乎并不是特定于浏览器。 我也无法弄清楚区别在哪里,如果不是视口的大小,是否还有另外一个因素使得结果有所不同?

任何有识之士将不胜感激。


更新:

它不是$(window).width()$(window).height()正在改变的值。 这是我用来存储上述值的variables的值。

这不是滚动条的值,当variables值改变时,不会出现滚动条。 这里是我的代码来存储在我的variables的值(我正在做,所以他们更短)。

(所有这些在$(document).ready()

//最初声明variables在.ready()可见,

 var windowWidth = $(window).width(); //retrieve current window width var windowHeight = $(window).height(); //retrieve current window height var documentWidth = $(document).width(); //retrieve current document width var documentHeight = $(document).height(); //retrieve current document height var vScrollPosition = $(document).scrollTop(); //retrieve the document scroll ToP position var hScrollPosition = $(document).scrollLeft(); //retrieve the document scroll Left position function onm_window_parameters(){ //called on viewer reload, screen resize or scroll windowWidth = $(window).width(); //retrieve current window width windowHeight = $(window).height(); //retrieve current window height documentWidth = $(document).width(); //retrieve current document width documentHeight = $(document).height(); //retrieve current document height vScrollPosition = $(document).scrollTop(); //retrieve the document scroll ToP position hScrollPosition = $(document).scrollLeft(); //retrieve the document scroll Left position }; //end function onm_window_parameters() 

我插入了一个alert语句来探测上面的variables和它们应该保持的值。 $(item).param()值保持一致,但我的variables由于我无法弄清楚的原因而改变。

我已经寻找了我的代码可能正在改变所讨论的variables的值的地方,而不是仅仅检索它们的设置值,而是找不到任何值。 如果可能的话,我可以把整个post贴出来。

我想你看到的是滚动条的隐藏和显示。 下面是一个显示宽度变化的快速演示 。

顺便说一句:你需要不断轮询吗? 您可能可以优化您的代码以在resize事件上运行,如下所示:

 $(window).resize(function() { //update stuff }); 

尝试使用一个

  • $(window).load事件

要么

  • $(document).ready

    因为初始值可能是不稳定的,因为在parsing期间或DOM负载期间发生的变化。

请注意,如果问题是由滚动条出现引起的,

 body { overflow: hidden; } 

在你的CSS可能是一个简单的修复(如果你不需要页面滚动)。

我有一个非常类似的问题。 当我刷新我的页面时,我的height()值不一致。 (这不是我的variables造成的问题,这是实际的身高值。)

我注意到,在我的页面头,我先调用我的脚本,然后我的CSS文件。 我切换,以便首先链接的CSS文件,然后脚本文件,似乎已经解决了这个问题。

希望有所帮助。