screen.width/screen.height not updating after screen rotation

前提是你 提交于 2021-02-18 04:52:18

问题


I'm experiencing this problem on an iPhone device (iPhone 7, iOS 10, but also other iPhones too): in javascript, if I intercept the orientationchange event, inside the handler, screen.width and screen.height remain the same (as before rotation).

Since this may depend from the viewport settings, this is how my viewport is declared in the .html file:

<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=no" />

Everything works fine in Chrome's simulated visualization.

Thanks in advance for your help.


回答1:


As far as I know screen the width/height will not change in the device after rotation. To check if the device is rotated you could read these properties

  1. window.orientation: This value change from 0 to +90/-90
  2. window.innerHeight/innerWidth: This values are swapped
  3. document.documentElement.clientHeight/clientWidth: This values are swapped

Unfortunately, this behavior is not consistent across all Android/iOS/Window devices. I think it's pretty explained in this figure .




回答2:


iOS used to return the size of the screen as if it was in portrait. They changed it on iOS 8 (on the native classes), but they might have forgotten to do it for Safari, or maybe they kept it that way for compatibility.

If you want the real size based on the orientation you can use window.innerWidth and window.innerHeight

I get the same values with or without the viewport meta tag

It works fine on Chrome simulated visualization because it return the screen size of the simulated visualization, as it should be, but it doesn't simulate the OS where it should be running based on the device, so you won't get the same values as on a real device (in this case in which the real device doesn't return good values)




回答3:


CSS can't detect the orientation change.

Use JavaScript to get the orientation change.

Add the function as

window.addEventListener("orientationchange", function() {
  document.body.style.width = window.innerWidth;
});

This will add an event Handler to window to change the width of body when the orientation is changed.

More reference on orientationchange




回答4:


jQuery mobile has onOrienntetionChange event that handle orientation changing event,and there is $(window).orientationchange(); function to change orientation manually.



来源:https://stackoverflow.com/questions/44484547/screen-width-screen-height-not-updating-after-screen-rotation

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