问题
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