检测Mac和Surface上的窗口分辨率



在我的Surface和MacBook上,我将分辨率设置为2160x1440,但我的代码:

$(window).height(); //return 960
$(window).height(); //return 1440

我已经在Windows上测试过了,它工作正常。这里的问题是什么?

这是因为您使用的是视网膜显示器。

必须使用window.devicePixelRatio来计算实际分辨率。

编辑:很多关于分辨率和设备像素比的信息在http://ryanve.com/lab/resolution/

注意事项:

  • devicePixelRatio定义因平台而异。
  • window.devicePixelRatio相当于dppx
  • window.devicePixelRatio随桌面缩放而变化,但在移动设备上保持静态。设备像素比媒体查询也有所不同。

try window.devicePixelRatio

window.screen.width * window.devicePixelRatio; //Screen Width
window.screen.height * window.devicePixelRatio; //Screen  Height

检查你的视口高度使用window.innerHeightwindow.outerHeight。如果您想检查屏幕分辨率,只需使用window.screen.height。纯JavaScript,不需要jQuery。

请记住,逻辑像素与物理像素是不一样的,特别是在Mac的Retina显示器上。

Kevin实际上是对的,但是他发布的解决方案不是跨浏览器友好的。这实际上是亚当的答案的一个稍微修改的版本,但它应该支持更多的浏览器。它使用媒体查询来确定像素比是多少,但请记住,如果你将一个元素设置为那个大小,它实际上会在Retina或其他高密度显示器上显示得很大。

var multiplier = 1;
if ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 124dpi), only screen and (min-resolution: 1.3dppx), only screen and (min-resolution: 48.8dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 1.3)) {
    multiplier = 2;
}
var width = $(window).width() * multiplier;
var height = $(window).height() * multiplier;

我正在使用这个:

  var screenResolution = window.screen.width + "x" + window.screen.height;
  var viewportSize = getViewport();
  var getViewport = function(a) {
             var c = document.documentElement,  e = document.body, g = e && e.clientWidth && e.clientHeight,  ca = [];
             c && c.clientWidth && c.clientHeight && ("CSS1Compat" === document.compatMode || !g) ? ca = [c.clientWidth, c.clientHeight] : g && (ca = [e.clientWidth, e.clientHeight]);
             c = 0 >= ca[0] || 0 >= ca[1] ? "" : ca.join("x");
             return c;
        }

这是未经测试的,但您应该能够做这样的事情:

actual_resolution = $(window).height() * $(window).devicePixelRatio;

使用devicePixelRatio,您必须获得正确的分辨率。

var devicePixelRatio = window.devicePixelRatio || 1;
console.log(window.screen.width * devicePixelRatio); // Width
console.log(window.screen.height * devicePixelRatio); // Height

这是我尝试跨浏览器/平台的dpi解决方案。它使用1英寸的固定宽度/高度单元格来确定其中的像素数。

<script> 
function dpi(){ 
   var res={},div=document.createElement("div");
   div.style.position="absolute";
   div.style.width="1in";
   div.style.height="1in";
   div.style.left="-100%";
   div.style.top="-100%";
   document.getElementsByTagName('body')[0].appendChild(div);
   res["xdpi"]=div.offsetWidth;
   res["ydpi"]=div.offsetHeight; 
   div="";
   return res; 
} 
res=dpi();
alert("xdpi="+res.xdpi+", ydpi="+res.ydpi) 
</script>

最新更新