jquery $(window).width()和$(window).height()在视口未调整大小时返回不同的值

Man*_*eks 105 jquery height resize viewport width

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

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

想知道是否有任何特殊情况,任何人都知道这种情况何时发生,或者这是否就是这样.显示的尺寸差异为20px或更小.它发生在Mac OS X 10.6.2上的Safari 4.0.4,Firefox 3.6.2和Chrome 5.0.342.7 beta中.我还没有测试其他浏览器,因为它似乎并不特定于浏览器.我也无法弄清楚差异取决于什么,如果它不是视口大小,是否会有另一个因素导致结果不同?

任何见解将不胜感激.


更新:

这不是值$(window).width(),并$(window).height()正在改变.这是我用来存储上述值的变量的值.

它不是影响值的滚动条,变量值更改时不会显示滚动条.这是我的代码将值存储在我的变量中(我正在做的只是因为它们更短).

(这一切都在$(document).ready())

//最初声明变量对于其中的otehr函数是可见的 .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()
Run Code Online (Sandbox Code Playgroud)

我插入了一个警告语句来探测上面的变量与它们应该持有的值.该$(item).param()值保持一致,但我的变量发生变化的原因,我想不通.

我已经找到了我的代码可能会改变有问题的变量值的地方,而不是只检索它们的设置值而且找不到.如果可能的话,我可以将整个shebang发布到某个地方.

Nic*_*ver 98

我认为你所看到的是隐藏和显示滚动条. 这是一个显示宽度变化的快速演示.

暂且不说:你需要经常轮询吗?您可以优化代码以在resize事件上运行,如下所示:

$(window).resize(function() {
  //update stuff
});
Run Code Online (Sandbox Code Playgroud)


Alb*_*ozi 9

尝试使用

  • $(window).load 事件

要么

  • $(document).ready

    因为在解析期间或在DOM加载期间发生的更改,初始值可能是不定的.