简体   繁体   中英

How to detect the screen DPI using JavaScript

The only way I found till now, is getting the offsetWidth, offsetHeight of a test div element with height and width of one inch: http://www.infobyip.com/detectmonitordpi.php

Is there a way to detect the screen DPI via JavaScript instead?

Thanks,

Atara.

In webkit you can detect if your user has a so called "high dpi screen" by simply retrieving the value from:

window.devicePixelRatio

Normal dpi screens will return 1. The iPhone 4 will return 2, but numbers like 1.8 or 2.12 are also possible.

<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
    dpi_x = document.getElementById('testdiv').offsetWidth;
    dpi_y = document.getElementById('testdiv').offsetHeight;
</script>

Then you can use JQuery to send dpi_x and dpi_y this to to your server

http://jsfiddle.net/sxfv3/

There is, so far, no standard and supported-everywhere solution.

window.devicePixelRatio , as suggested by laurens peeters, does work if you don't care about IE, or any browser from the ancient times, like early January 2013 (eg, Firefox 17).

See Cross Browser Retina/High Resolution Media Queries (and various comments and links there) for how to get this information as of late 2012, but you'll have to keep searching again, and adjusting your code, every so often until something finally gets standardized, and implemented in every browser, with widespread-enough version adoption that you can stop caring about older versions…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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