屏幕.宽度/屏幕.高度在屏幕旋转后不更新



我在iPhone设备(iPhone 7,iOS 10,以及其他iPhone(上遇到了这个问题:在javascript中,如果我拦截了orientationchange事件,在处理程序中,screen.width和screen.height保持不变(与旋转前一样(。

由于这可能取决于视口设置,因此我的视口在.html文件中声明的方式如下:

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

在Chrome的模拟可视化中一切正常。

提前感谢您的帮助。

据我所知,屏幕旋转后设备的宽度/高度不会改变。要检查设备是否已旋转,您可以读取这些属性

  1. 窗口方向:此值从 0 更改为 +90/-90
  2. window.innerHeight/innerWidth:这些值被交换
  3. document.documentElement.clientHeight/clientWidth:这些值被交换

不幸的是,这种行为在所有Android/iOS/Window设备上并不一致。我认为这在图中得到了很好的解释.

iOS过去常常返回屏幕的大小,就好像它是纵向的一样。他们在iOS 8(在本机类上(上更改了它,但他们可能忘记了为Safari执行此操作,或者为了兼容性,他们保持了这种方式。

如果你想要基于方向的实际尺寸,你可以使用 window.innerWidthwindow.innerHeight

我得到有或没有视口元标记的相同值

它在Chrome模拟可视化上工作正常,因为它返回模拟可视化的屏幕大小,因为它应该是,但它不会模拟它应该基于设备运行的操作系统,因此您不会获得与真实设备上相同的值(在这种情况下,真实设备不返回良好的值(

CSS 无法检测到方向变化。

使用 JavaScript 来更改方向。

将函数添加为

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

这将向window添加一个event Handler,以便在方向更改时更改bodywidth

有关orientationchange的更多参考

资料

jQuery移动版有onOrienntetionChange处理方向改变事件的事件,并且有手动改变方向$(window).orientationchange();函数。

考虑到这是移动和iOS设备的行为,此功能可能会为您提供帮助。验证设备、方向和操作系统。

import isMobile from 'ismobilejs'
/* For practical example: @see: https://www.npmjs.com/package/ismobilejs */
function windowSize() {
    let [_width, _height] = [window.innerWidth, window.innerHeight]
    // detect if device is mobile or tablet
    if (isMobile(window.navigator).any) {
        [_width, _height] = [window.screen.width, window.screen.height]
        // detect if device is iOS and horizontal orientation
        if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
            // Horizontal orientation are equal to -90 or 90 degrees
            if (Math.abs(window.orientation) == 90) {
                _width = window.screen.height
                _height = window.screen.width
            }
        }
    }
    return {
        width: _width,
        height: _height
    }
}

在移动设备上方向更改或在桌面上调整窗口大小时调用此函数。

let _windowSize = windowSize() // Return { width: realWidth, height: realHeight }
if (isMobile(window.navigator).any) {
    window.addEventListener("resize", () => { _windowSize = windowSize() })
} else {
    window.addEventListener("orientationchange", () => { _windowSize = windowSize() })
}

最新更新