jquery $(window).width() and $(window).height() return different values when viewport has not been resized

前端 未结 4 699
野性不改
野性不改 2020-12-04 07:45

I am writing a site using jquery that repeatedly calls $(window).width() and $(window).height() to position and size elements based on the viewport

相关标签:
4条回答
  • 2020-12-04 08:04

    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.

    0 讨论(0)
  • 2020-12-04 08:13

    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
    });
    
    0 讨论(0)
  • 2020-12-04 08:13

    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.

    0 讨论(0)
  • 2020-12-04 08:16

    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).

    0 讨论(0)
提交回复
热议问题