繁体   English   中英

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

[英]screen.width/screen.height not updating after screen rotation

我在 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. window.orientation :这个值从 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 mobile 有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() })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM