2017-05-03 39 views
1

我目前使用從this answer2017年所有瀏覽器(尤其是Android手機)上檢測屏幕寬度和高度的可靠代碼?

var ratio = window.devicePixelRatio || 1; 
var w = screen.width * ratio; 
var h = screen.height * ratio; 

此代碼它適用於桌面Firefox,但不是在我的Android瀏覽器(股票或鉻我的三星Galaxy S5手機上更新到Android 5)。我得到的是320x640而不是1280x1920。

是否有可靠的解決方案來檢測所有設備上的屏幕尺寸&瀏覽器?我需要設備的屏幕寬度,而不是內部/客戶端寬度或其他東西。

如果這是不可能的,幾個評論說這是不可能的從有影響力的SO成員將工作正常 - 我可以證明這是我的客戶證明。

+0

檢查[此文件](https://github.com/tysonmatanich/GetDevicePixelRatio/blob/master/getDevicePixelRatio.js)這可能是一個潛在的解決方案。沒有自己測試過。這也出現在[這個問題](http://stackoverflow.com/questions/5063489/how-can-you-get-the-css-pixel-device-pixel-ratio),由abhinav sharma回答。 – andreim

+0

據我所知,這個問題沒有真正的解決方案@MarkoAvlijaš – NoOorZ24

+0

@andreim - 這是在我的手機上工作。你打算創建一個答案嗎? –

回答

1

一種解決方案來解決的設備像素比取得描述here

/*! GetDevicePixelRatio | Author: Tyson Matanich, 2012 | License: MIT */ 
(function (window) { 
    window.getDevicePixelRatio = function() { 
     var ratio = 1; 
     // To account for zoom, change to use deviceXDPI instead of systemXDPI 
     if (window.screen.systemXDPI !== undefined && window.screen.logicalXDPI !== undefined && window.screen.systemXDPI > window.screen.logicalXDPI) { 
      // Only allow for values > 1 
      ratio = window.screen.systemXDPI/window.screen.logicalXDPI; 
     } 
     else if (window.devicePixelRatio !== undefined) { 
      ratio = window.devicePixelRatio; 
     } 
     return ratio; 
    }; 
})(this); 

因此的完整代碼將是:

var ratio = window.getDevicePixelRatio(); 
var w = screen.width * ratio; 
var h = screen.height * ratio; 

注:該溶液也引用在此由abhinav sharma提供question answer

相關問題