這里所說的縮放不是指瀏覽器大小的縮放,而是指瀏覽器網頁內容的百分比縮放(按Ctrl和+號鍵或者-號鍵的縮放)。
檢測這種縮放有很種方法,QQ空間都通過flash來檢測瀏覽器是否處於縮放。這里提供javascript的方法來檢測瀏覽器的縮放。
對於 IE6,就直接無視了,因為 IE6 只能對文本進行縮放。
先來說說瀏覽器提供的標准檢測接口,window.devicePixelRatio 是設備上物理像素和設備獨立像素的比例,該屬性就可以用於檢測網頁是否被縮放了。在普通的 PC 瀏覽器上,在默認無縮放的情況下其默認值是 1。目前Firefox、chrome等都得到了很好的支持。
接下來該說說 IE 的處理方法了。IE 提供了 window.screen.deviceXDPI 和 window.screen.logicalXDPI 兩個屬性,deviceXDPI 就是對應的設備上的物理像素,而 logicalXDPI 就是對應了設備獨立像素的比例。估計標准的檢測接口也只是基於 IE 這種方法的一種改進。這兩個屬性在 windows XP+ 以上的系統上的默認值都是 96,因為系統默認的就是 96dpi 。
對於以上兩種都不支持的瀏覽器,還可以利用window.outerWidth 和 window.innerWidth 這兩個屬性。outerWidth 返回的是窗口元素的外部實際寬度,innerWidth 返回的是窗口元素的內部實際寬度,這兩個寬度都包含了滾動條在內的寬度。
有了這些屬性基本就可以搞定 PC 瀏覽器上常見的瀏覽器了。實現代碼如下:
方法一:
detectZoom 函數的返回值如果是 100 就是默認縮放級別,大於 100 則是放大了,小於 100 則是縮小了。
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;
};
var obj = {'window.devicePixelRatio':window.devicePixelRatio,'screen.deviceXDPI / screen.logicalXDPI':screen.deviceXDPI / screen.logicalXDPI,
'window.outerWidth / window.innerWidth':window.outerWidth / window.innerWidth,
'document.documentElement.offsetHeight / window.innerHeight':document.documentElement.offsetHeight / window.innerHeight,
'window.top.outerWidth / window.top.innerWidth':window.top.outerWidth / window.top.innerWidth}
function print(obj){
var s = '';
for(var key in obj){
s+=key;
s+=' : ';
s+=obj[key];
s+='\n\r'
}
document.write(s)
}
print(obj)
