How to detect the screen DPI using JavaScript

前端 未结 3 500
余生分开走
余生分开走 2020-12-03 07:54

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:

相关标签:
3条回答
  • 2020-12-03 08:01
    <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/

    0 讨论(0)
  • 2020-12-03 08:05

    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 (e.g., 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…

    0 讨论(0)
  • 2020-12-03 08:22

    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.

    0 讨论(0)
提交回复
热议问题