Getting inconsistent results from window.innerWidth in Mobile Safari

会有一股神秘感。 提交于 2020-01-25 00:51:06

问题


I'm using this javascript to detect the browser width:

$(document).ready(function(){ var width = window.innerWidth; });

It appears to be giving inconsistent results. I've made a working codepen here. by repeatedly refreshing the full-page view in mobile Safari I've received both of the following results:

It jumps back and forth inconsistently, and appears to be exacerbated by a larger page size (hence all the images). Sometimes it will only return one result until I kill the app and re-open it.

Is there a better way to get the width of the browser?

Notes:

  • I've added this to the head: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
  • Using $(window).width() isn't really an option for me because it doesn't account for scrollbars
  • I know I could put the js in a timeout function, but this solution is problematic for me since I'm storing the result in a variable that I'm using in various places throughout the website.
  • I'm using an iPhone 5 running iOS 9.2

Thanks!


回答1:


Safari gets inconsistent widths in vanilla javascript because of the resolution. JQuery usually standardised this. Try using:

$(window).width()

This should give you the right width.



来源:https://stackoverflow.com/questions/34644764/getting-inconsistent-results-from-window-innerwidth-in-mobile-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!