hi,欢迎访问本站!
当前位置: 首页Web前端正文

js检测浏览器是否缩放以及缩放的比例

墨初 Web前端 831阅读

PC端的浏览器可以通过一些特定的组合键或设置来实现浏览器中的页面缩放的。但页面缩放后有可能造成页网页布局的混乱,为了防止用户在缩放页面时页面的元素布局发生排版的混乱,就需要用js代码进行判断,来修正页面的布局。

js 检测浏览器是否开启了缩放

例:

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) { //IE
        ratio = screen.deviceXDPI / screen.logicalXDPI;
    }
} else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
    ratio = window.outerWidth / window.innerWidth;
}
if(ratio == 1){ 
    console.log('网页正常大小!');
} else if(ratio > 1){
    console.log('网页被放大!');
}else{
    console.log('网页被缩小!');
}

代码理解

1、浏览器的标准检测接口,window.devicePixelRatio 是设备上物理像素和设备独立像素的比例,该属性可以用于检测网页是否被缩放了。

2、在PC的浏览器上,window.devicePixelRatio 在无缩放的情况下的值为1,小于1则为缩小状态,大于1则为放大状态!

3、IE浏览器提供了 window.screen.deviceXDPI 和 window.screen.logicalXDPI 两个属性,deviceXDPI 就是对应的设备上的物理像素,而 logicalXDPI 就是对应了设备独立像素的比例。

4、对于上面两种接口都不支持的浏览器,可以使用 window.outerWidth 和 window.innerWidth 这两个属性。

js 检测浏览器的缩放比例

例:

function detectZoom() 
{
    var ratio = 0,   screen = window.screen, 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;
};
//如果值为 100,则为正常大小
console.log(detectZoom());

PS:

在某此情况下是无法准备的检测到浏览器的缩放比例的。

1、个人测试在mac系统下检测浏览器缩放会有一些误差

2、如果系统级的缩放会造成误差

声明:无特别说明,转载请标明本文来源!
相关推荐