How to reliably get screen width WITH the scrollbar

前端 未结 9 1208
抹茶落季
抹茶落季 2020-12-03 21:38

Is there a way to reliably tell a browser\'s viewport width that includes the scrollbar, but not the rest of browser window)?

None of the properties listed here tell

9条回答
  •  臣服心动
    2020-12-03 21:59

    I figured out how to accurately get the viewport width WITH the scrollbar using some code from: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript

    Put this inside your $(document).ready(function()

    $(document).ready(function(){
        $(window).on("resize", function(){
          function viewport() {
              var e = window, a = 'inner';
              if (!('innerWidth' in window )) {
                  a = 'client';
                  e = document.documentElement || document.body;
              }
              return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
          }
        });
        // Get the correct window sizes with these declarations
        windowHeight = viewport().height;
        windowWidth = viewport().width;  
    });
    

    What it Does:

    When your page is 'ready' or is resized, the function calculates the correct window height and width (including scrollbar).

提交回复
热议问题