您的位置:首页 > Web前端

浏览器缩放检测

2018-05-30 15:19 399 查看
在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系统本身的缩放也会影响此缩放判断
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  浏览器 缩放 前端