Jquery $(window) . width()和 $(window) . height()在 viewport 没有调整大小时返回不同的值

我正在使用 jquery 编写一个站点,该站点反复调用 $(window).width()$(window).height()来根据 viewport 大小定位和调整元素的大小。

在故障排除中,我发现当视口没有调整大小时,在对上述 jquery 函数的重复调用中,我得到的视口大小报告略有不同。

想知道有没有什么特殊情况人们知道什么时候会发生这种情况,或者这就是事情的本来面目。报告的大小差异显示为20px 或更小。它发生在 Safari 4.0.4,Firefox 3.6.2和 Chrome 5.0.342.7 beta 版的 Mac OS X 10.6.2上。我还没有测试其他浏览器,因为它看起来不是特定于浏览器的。我也无法弄清楚这种差异取决于什么,如果不是视窗大小,是否还有其他因素使得结果不同?

有任何线索都可以。


更新:

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

影响值的不是滚动条,当变量值更改时不会出现滚动条。下面是在变量中存储值的代码(我这样做是为了缩短变量的长度)。

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

//最初声明变量对于 .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()

我插入了一个警告语句来检查上面的变量是否与它们应该保存的值相对应。$(item).param()值保持一致,但我的变量变化的原因我不能理解。

我一直在寻找我的代码可能会改变所讨论的变量值的地方,而不是仅仅检索它们的设置值,却什么也找不到。如果有可能的话,我可以把整个东西都贴在某个地方。

457730 次浏览

I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.

As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:

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

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

Try to use a

  • $(window).load event

or

  • $(document).ready

    because the initial values may be inconstant because of changes that occur during the parsing or during the DOM load.

Note that if the problem is being caused by appearing scrollbars, putting

body {
overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).