在pc端項目的開發中,經常會遇到用戶瀏覽頁面卻發現佈局出現混亂的情況,這時候排查可能是網頁的縮放引起的,所以在頁面加載的時候添加了瀏覽器的縮放檢測提示功能。
採用的檢測方式裏用到一個屬性 window.devicePixelRatio ,以下是摘自張鑫旭的 設備像素比devicePixelRatio簡單介紹,有興趣可以看下;
window.devicePixelRatio是設備上物理像素和設備獨立像素(device-independent pixels (dips))的比例。
公式表示就是:window.devicePixelRatio = 物理像素 / dips
和screen.deviceXDPI 、 screen.logicalXDPI 都是爲了計算縮放率
代碼如下:
// 瀏覽器縮放檢測
function detectZoom (){
var ratio = 0,
screen = window.screen,
ua = navigator.userAgent.toLowerCase();
if (window.devicePixelRatio !== undefined) {
ratio = window.devicePixelRatio;
}else if (~ua.indexOf('msie')) { // ie
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;
};
之後可以使用這個比率來進行提示重置縮放,
另外經過檢測的是chrome瀏覽器 win系統本身的縮放也會影響此縮放判斷