2013-05-05 119 views

回答

7
window.devicePixelRatio = window.devicePixelRatio || 
Math.round(window.screen.availWidth/document.documentElement.clientWidth) 

得到它從http://blogs.windows.com/windows_phone/b/wpdev/archive/2012/11/08/internet-explorer-10-brings-html5-to-windows-phone-8-in-a-big-way.aspx

+1

這回退到似乎** **不正確,因爲'availWith'和'clientWidth'都在[逢低](http://www.quirksmode.org/blog/archives/2012/06/devicepixelrati.html),也因爲'clientWidth'是一個動態值。 'devicePixelRatio'的CSS單元是[dppx](http://www.w3.org/TR/css3-values/#dppx)。 – ryanve 2013-09-17 20:42:43

+3

'devicePixelRatio'可能是一個小數值,所以'Math.round'不合適,但不管。如果您不確定該窗口是否最大化(這意味着在所有桌面客戶端上),請不要使用回退。而且,'document.documentElement.clientWidth'不包括桌面瀏覽器上的滾動條寬度。 – MaxArt 2014-03-20 08:49:47

+0

@MaxArt,只要你確定就編輯我的答案。 – user960567 2014-03-20 09:57:43

17

對於IE回落,臺式機和移動,使用:

window.devicePixelRatio = window.devicePixelRatio || 
          window.screen.deviceXDPI/window.screen.logicalXDPI; 
+2

這應該是正確的答案..它是現貨。 – tremor 2015-03-05 14:47:18

+1

這裏是官方參考:https://msdn.microsoft.com/en-us/library/dn255104(v=vs.85).aspx – user3526 2015-08-10 11:47:57

3

我發現,在諾基亞Lumia 1230 window.devicePixelRatio甚至返回1屬性如果該值顯然不正確。測試window.screen.deviceXDPI/window.screen.logicalXDPI返回1.52083333。 所以先使用window.devicePixelRatio不是一個好主意。

我建議如下:

function getDevicePixelRatio(){ 
    var pixelRatio = 1; // just for safety 
    if('deviceXDPI' in screen){ // IE mobile or IE 
     pixelRatio = screen.deviceXDPI/screen.logicalXDPI; 
    } else if (window.hasOwnProperty('devicePixelRatio')){ // other devices 
     pixelRatio = window.devicePixelRatio; 
    } 
    return pixelRatio ; 
} 

出於某種原因,用最好的方法來測試的deviceXDPI的畫面對象存在:

if(screen.hasOwnProperty('deviceXDPI')) {// IE mobile or IE 

沒有這方面的工作電話。

2

其實,以前的答案都不是正確的。下面所有的測試均在的Lumia由具有480×800的LCD屏520個電話:

WP8/IE移動10:

  • window.devicePixelRatio =未定義
  • window.inner/outerWidth /高度= 320 * 485
  • 屏幕。[無濟於事]寬度/高度= 330 * 549
  • document.body.clientWidth /高度= 320 * 486
  • screen.device/logicalXDPI =九十六分之一百四十= 1.45833 ..

預期devicePixelRatio是三百二十分之四百八十〇= 1.5其可以通過下式計算:

Math.round(screen.availWidth * screen.deviceXDPI/screen.logicalXDPI/4) * 4/document.body.clientWidth 

(需要舍入以獲得一個有效的液晶屏尺寸)

WP8.1/IE移動11:

  • window.devicePixelRatio = 1.42177 ...
  • window.outerWidth /身高= 338 * 512
  • window.innerWidth /高度= 320 * 485
  • 屏幕。[無濟於事]寬度/高度= 338 * 563
  • document.body.clientWidth /高度= 320 * 486
  • screen.device/logicalXDPI = 136/96 = 1.4166 ..

預期devicePixelRatio是(再次)480/320 = 1。5其可以通過下式計算:

Math.round(screen.availWidth * window.devicePixelRatio/4) * 4/document.body.clientWidth 

因此,即使window.devicePixelRatio存在它會給你DOM屏幕大小和液晶屏尺寸之間的比率,但是,DOM屏幕尺寸大於可用視口較大尺寸。如果您想知道CSS像素與設備像素之間的確切比例,則必須進行上述計算。此外,這些計算在縱向模式下有效。在橫向模式下使用screen.availHeight(DOM屏幕尺寸在IE Mobile上不改變方向變化)。