首先說明,這里所說的瀏覽器狀態是指用戶點擊瀏覽器左上角的放大加號/減號所產生的頁面整體變大變小的情況(快捷鍵: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%") }