window.screen.width和window.screen.height在iPad3上不起作用

window.screen.width and window.screen.height not working on iPad 3

本文关键字:window screen 不起作用 iPad3 height width      更新时间:2023-11-07

我正在使用函数

window.screen.width
window.screen.height

以检测用户的屏幕分辨率。它们在个人电脑上很有魅力,但在iPad3上却没有。它们输出768和1024,而不是2048和1536。

有人能帮帮我吗?提前感谢

是的。欢迎来到移动设备的有趣世界!

iPad3(和其他视网膜设备)使用设置为2window.devicePixelRatio来显示它们具有不同的css像素和逻辑像素。iPad3仍然报告1024×768,因为这是CSS像素的数量。

另一个令人困惑的来源是,一些Android设备报告了视口宽度,而另一些报告了物理宽度,这意味着如果你问一些Android设备,如果文档很长,window.screen.height将是成千上万。

简而言之,对于您的问题,使用window.devicePixelRatio作为乘数。我会用之类的东西

if(!window.devicePixelRatio) {
    window.devicePixelRatio = 1;
}

确保如果未设置,则在开始之前将其声明为1。

if(window.devicePixelRatio !== undefined) {
    dpr = window.devicePixelRatio;
} else {
    dpr = 1;
}
var screen_width = window.screen.width * dpr;
var screen_height = window.screen.height * dpr;

这个解决方案非常有效。