js获取浏览器的缩放状态,浏览器右上角的百分比缩放后的状态

首先说明,这里所说的浏览器状态是指用户点击浏览器左上角的放大加号/减号所产生的页面整体变大变小的情况(快捷键:Ctrl+加号或 Ctrl+减号 或 Ctrl+滚轮上下)

实现代码如下:

detectZoom 函数的返回值如果是 100 就是默认缩放级别,大于 100 则是放大了,小于 100 则是缩小了。

 1 function detectZoom (){
 2   var ratio = 0,
 3     screen = window.screen,
 4     ua = navigator.userAgent.toLowerCase();
 5   
 6    if (window.devicePixelRatio !== undefined) {
 7       ratio = window.devicePixelRatio;
 8   }
 9   else if (~ua.indexOf('msie')) {
10     if (screen.deviceXDPI && screen.logicalXDPI) {
11       ratio = screen.deviceXDPI / screen.logicalXDPI;
12     }
13   }
14   else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
15     ratio = window.outerWidth / window.innerWidth;
16   }
17     
18    if (ratio){
19     ratio = Math.round(ratio * 100);
20   }
21     
22    return ratio;
23 };
var ratio = detectZoom ()

// 打印当前缩放值
console.log(ratio)

// 判断是否缩放

if(ratio > 100){
  console.log("放大啦")  
}else if(ratio < 100){
    console.log("缩小了")
}else{
  console.log("100%")      
}

 

posted @ 2019-07-01 10:00  Gordon-Guo  阅读(2375)  评论(0编辑  收藏  举报