在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系统本身的缩放也会影响此缩放判断