screen.width / screen.height在屏幕旋转后未更新

时间:2017-06-11 13:45:29

标签: javascript ios iphone screen-orientation

我在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的模拟可视化中一切正常。

提前感谢您的帮助。

5 个答案:

答案 0 :(得分:13)

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

  1. window.orientation :此值从0更改为+ 90 / -90
  2. window.innerHeight / innerWidth :此值已交换
  3. document.documentElement.clientHeight / clientWidth :此值已交换
  4. 不幸的是,这种行为在所有Android / iOS / Window设备上都不一致。我认为在this figure中解释得非常好。

答案 1 :(得分:6)

iOS用于返回屏幕大小,就像它是纵向一样。 他们在iOS 8(在本地类上)改变了它,但他们可能忘记为Safari做这件事,或者他们可能保持这种兼容性。

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

我使用或不使用视口元标记

获得相同的值

它可以在Chrome模拟可视化中正常工作,因为它会返回模拟可视化的屏幕大小,但它不会根据设备模拟应该运行的操作系统,因此您赢了&# 39; t得到与真实设备相同的值(在这种情况下,真实设备不会返回好的值)

答案 2 :(得分:0)

jQuery mobile有onOrienntetionChange事件处理方向更改事件,并且$(window).orientationchange();函数可以手动更改方向。

答案 3 :(得分:0)

CSS无法检测方向变化。

使用JavaScript获取方向更改。

将功能添加为

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

当方向发生变化时,这会向event Handler添加window以更改width body

有关orientationchange

的更多参考资料

答案 4 :(得分:0)

考虑到这是移动设备和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() })
}