我們在開發一些前端頁面的時候,會考慮到一些設備屏幕的兼容性問題,這個時候需要根據屏幕的分辨率以及縮放比例來進行實時的寬高設定,所以我總結了用JavaScript方法進行獲取用戶電腦屏幕的分辨率和縮放比例的數據:
獲取屏幕縮放比例
//獲取屏幕縮放比例
function getRatio()
{
var ratio=0;
var screen=window.screen;
var ua=navigator.userAgent.toLowerCase();
if(window.devicePixelRatio !== undefined)
{
ratio=window.devicePixelRatio;
}
else if(~ua.indexOf('msie'))
{
if(screen.deviceXDPI && screen.logicalXDPI)
{
ratio=screen.deviceXDPI/screen.logicalXDPI;
}
}
else if(window.outerWidth !== undefined && window.innerWidth !== undefined)
{
ratio=window.outerWidth/window.innerWidth;
}
if(ratio)
{
ratio=Math.round(ratio*100);
}
return ratio;
}
獲取分辨率
屏幕分辨率的高:window.screen.height*getRatio()/100 //乘以縮放比例爲真實的像素
屏幕分辨率的寬:window.screen.width*getRatio()/100 //乘以縮放比例爲真實的像素
屏幕可用工作區高度:window.screen.availHeight;
屏幕可用工作區寬度:window.screen.availWidth;