Mobile Safari window reports 980px

前端 未结 3 1318
Happy的楠姐
Happy的楠姐 2021-02-14 13:46

Why does this report 980 on the iPhone 4? I thought it would be 960 or 640.

alert($(window).width());
相关标签:
3条回答
  • 2021-02-14 13:52

    You're getting the default viewport setting. See Apple iOS docs - meta tag and search for 'viewport'.

    Property Description

    width The width of the viewport in pixels. The default is 980. The range is from 200 to 10,000. You can also set this property to the constants described in “number.” Available in iOS 1.0 and later.

    To get the device width, as per the docs:

    For example, to set the viewport width to the width of the device, add this to your HTML file:

    <meta name="viewport" content="width=device-width" />
    
    0 讨论(0)
  • 2021-02-14 13:56

    Have you tried the following?

    alert($(document).width());
    
    0 讨论(0)
  • 2021-02-14 14:14

    In safari the default the window width is 980px, so if your javascript begins executing before the window has loaded the the width will be 980px, even though your viewport meta tag specifies the width as 'device-width'.

    If you find that adding the meta tag <meta name="viewport" content="width=device-width" /> doesn't fix your problem, then make sure your Javascript code is executing only after the window has loaded.

    In vanilla Javascript:

    console.log(window.innerWidth) // might be the default width
    
    window.onload= function () {
      console.log(window.innerWidth) // should now be device width
      //... your code here ...
    
    }
    

    Alternatively, if using jQuery:

    console.log(window.innerWidth) // might be the default width
    
    $( document ).ready(function () {
      console.log(window.innerWidth) // should now be device width
      //... your code here ...
    })
    
    0 讨论(0)
提交回复
热议问题