javascript 使用javascript以英寸而不是像素为单位查找屏幕尺寸
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23606069/
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
find screen dimensions in inches not pixels using javascript
提问by stackunderflow
I was reading many questions on SO regarding best ways to detect screen size in pixels which is ultimately dependant on resolution to find the actual screen size.
我正在阅读有关 SO 的许多问题,这些问题是关于以像素为单位检测屏幕尺寸的最佳方法,这最终取决于分辨率以找到实际屏幕尺寸。
I know some mobile devices have small screen (say 4inch) yet the resolution is high. While some devices r having large screen (say 7inch tab) yet the resolution is low.
我知道有些移动设备屏幕小(比如 4 英寸)但分辨率很高。虽然某些设备具有大屏幕(例如 7 英寸标签),但分辨率却很低。
So when you want to display your page to the user, you really need the screen size in inches or centimetres to give the best view comforting the eyes.
因此,当您想向用户显示您的页面时,您确实需要以英寸或厘米为单位的屏幕尺寸,以提供最舒适的视觉效果。
So I ask: Is there away to find out screen size of the device in inches not pixels ? I know it can be, provided that we know the resolution! !Bec we can calculate the size from screen width and height
所以我问:有没有办法找出设备的屏幕尺寸(以英寸而不是像素为单位)?我知道可以,前提是我们知道分辨率!!Bec 我们可以从屏幕宽度和高度计算尺寸
Appreciating any idea!
欣赏任何想法!
回答by Pete
once you have got the screen resolution in pixels, you can work out the dpi with a hidden div:
获得以像素为单位的屏幕分辨率后,您可以使用隐藏的 div 计算出 dpi:
<div id="dpi" style="height: 1in; width: 1in; left: 100%; position: fixed; top: 100%;"></div>
js
js
var dpi_x = document.getElementById('dpi').offsetWidth;
var dpi_y = document.getElementById('dpi').offsetHeight;
then work out the resolution in inches:
然后计算出以英寸为单位的分辨率:
var width = screen.width / dpi_x;
var height = screen.height / dpi_y;
回答by Kyle Wilson
Now, as far as I can tell there is no sure-fire way to accurately get the screen width of a device. Everything (including inches, 1in == 96px) is based in one way or another on screen resolution.
现在,据我所知,没有可靠的方法来准确获取设备的屏幕宽度。一切(包括英寸,1in == 96px)都以一种或另一种方式基于屏幕分辨率。
Now, I know this may not be the fix-all for everyone, but hopefully it helps a few people out there. It helped me, since I wanted my page to behave differently for mobile users, and my initial plan of attack was going to be based on screen size.
现在,我知道这可能不是解决所有人的问题,但希望它可以帮助一些人。它帮助了我,因为我希望我的页面对移动用户有不同的表现,而我最初的攻击计划将基于屏幕大小。
What I ended up doing was replacing the line
我最终做的是更换线路
if (screen.height <= 768)
with
和
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))
As a disclaimer, I should also mention that this was from an answer that is a few years old now, so some devices may not be covered.
作为免责声明,我还应该提到这是来自几年前的答案,因此可能未涵盖某些设备。