window.innerWidth in Chrome's device mode

后端 未结 4 2030
野的像风
野的像风 2021-01-08 00:29

When in google chrome\'s device mode, what does window.innerWidth return? Is it the viewport of the device (plus any scroll bars)?

I\'m getting different values for

相关标签:
4条回答
  • 2021-01-08 00:39

    enter image description here

    copy and paste your code and run... As you can see the pictures, It operates normally....

    0 讨论(0)
  • 2021-01-08 00:44

    I'm not sure if this is a recent update (since the last responses), but I was able to find the viewport height/width by using:

    window.screen.width
    

    and

    window.screen.height
    

    This was particularly useful when I was trying to test whether the screen was phone-sized or not.

    0 讨论(0)
  • 2021-01-08 00:46

    We're currently having success with something like:

        const widths = [window.innerWidth];
    
        if (window.screen?.width) {
          widths.push(window.screen?.width);
        }
    
        const width = Math.min(...widths);
    

    The conditional check is there because I'm not sure how widespread the screen width API is. You may need to adjust this not to use certain newer JS features depending on what devices you are targeting/your build process.

    This could potentially go a bit weird if you have a window that is wider than the screen, but for us that isn't a problem.

    This gives us a width that matches the one at the top of the Responsive screen tool, even when contents overflow horizontally. This is important for us because we needed the UI to change in order to prevent that overflow, but the overflow was interfering with the width number we used to trigger the adjustment.

    I'm not sure if this is important, but we are also using:

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    
    0 讨论(0)
  • 2021-01-08 00:54

    window.innerWidth and innerHeight return the dimensions of the visual viewport. In desktop browsers, this is generally the browser's window dimensions. On mobile the situation is a bit more complicated because of pinch zoom.

    When you load a page without a <meta name="viewport"> tag, a default layout width is used (e.g. Chrome uses 980px). When the browser loads the page it does so maximally zoomed out. It looks like your device size above has a width of 425px so the browser zooms out when the page is loaded to see the whole 980px. If you have content that's wider than this (e.g. your image) it'll zoom out even further. Seeing as how your window.innerWidth is 1248, that implies a scale factor of about 30%.

    tl;dr: innerWidth/innerHeight reflect viewport with the pinch-zoom factor applied and the page is loaded fully zoomed out.

    EDIT: This has since changed in Chrome. window.innerWidth now returns the layout viewport width. To get the visual viewport width, use window.visualViewport.width. See this article for more details.

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