javascript window.screen.width 和 window.screen.height 不适用于 iPad 3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11548003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.screen.width and window.screen.height not working on iPad 3
提问by Floppy88
I'm using the functions
我正在使用这些功能
window.screen.width
window.screen.height
to detect the screen resolution of the user. They work like a charm on PCs, but they don't on iPad 3. They output 768 and 1024 instead of 2048 and 1536.
检测用户的屏幕分辨率。它们在 PC 上很有效,但在 iPad 3 上却没有。它们输出 768 和 1024,而不是 2048 和 1536。
Can somebody help me, please? Thank you in advance
有人可以帮我吗?先感谢您
回答by Rich Bradshaw
Yep. Welcome to the interesting world of Mobile devices!
是的。欢迎来到有趣的移动设备世界!
The iPad 3 (and other retina devices) use window.devicePixelRatio
set to 2
to show that they have different css pixels to logical pixels. An iPad 3 still reports 1024 × 768, as that is the number of CSS pixels.
iPad 3(和其他视网膜设备)使用window.devicePixelRatio
set to2
来显示它们具有与逻辑像素不同的 css 像素。iPad 3 仍然报告 1024 × 768,因为这是 CSS 像素的数量。
As another source of confusion, some Android devices report the viewport width, and some the physical width, meaning that if you ask some Android devices, the window.screen.height
will be thousands and thousands if the document is long.
作为另一个混乱的来源,一些 Android 设备报告视口宽度,而一些报告物理宽度,这意味着如果你问一些 Android 设备,window.screen.height
如果文档很长,将会有成千上万。
In short, for your problem, use window.devicePixelRatio
as a multiplier. I'd use something like
简而言之,对于您的问题,请window.devicePixelRatio
用作乘数。我会使用类似的东西
if(!window.devicePixelRatio) {
window.devicePixelRatio = 1;
}
To ensure that if it isn't set that it's declared as 1 before you start.
确保如果未设置,则在开始之前将其声明为 1。
回答by Floppy88
if(window.devicePixelRatio !== undefined) {
dpr = window.devicePixelRatio;
} else {
dpr = 1;
}
var screen_width = window.screen.width * dpr;
var screen_height = window.screen.height * dpr;
This solution works perfectly.
该解决方案完美运行。