我想通过访问JavaScript的窗口对象属性,找出在浏览器窗口中显示的缩放级别。但是,我似乎找不到基于内部宽度、页面偏移等因素的正确数学公式来计算缩放级别。我找到了一个解决方案,但它使用了document.body.getBoundingClientRect调用,在我的情况下没有返回任何内容,而我也无法确定是否有适合的替代方法来从窗口属性中获取信息。我正在使用Safari浏览器。
我想通过访问JavaScript的窗口对象属性,找出在浏览器窗口中显示的缩放级别。但是,我似乎找不到基于内部宽度、页面偏移等因素的正确数学公式来计算缩放级别。我找到了一个解决方案,但它使用了document.body.getBoundingClientRect调用,在我的情况下没有返回任何内容,而我也无法确定是否有适合的替代方法来从窗口属性中获取信息。我正在使用Safari浏览器。
您可以通过比较以下各种属性来确定缩放级别,具体取决于您的浏览器:
window.outerWidth
(在Opera上)相比document.defaultView.getComputedStyle(document.documentElement, null).width
(在Safari、Chrome上)相比screen.deviceXDPI
和screen.logicalXDPI
(在IE8上)。这些值之间的比率就是当前的缩放级别(例如,2的比率表示200%的缩放)。
function getZoom(){
var ovflwTmp = $('html').css('overflow');
$('html').css('overflow','scroll');
var viewportwidth;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerWidth;
} else if (typeof(document.documentElement) != 'undefined' &&
typeof document.documentElement.clientWidth != 'undefined' &&
document.documentElement.clientWidth != 0) {
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
viewportwidth = document.documentElement.clientWidth;
} else {
// older versions of IE
viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
}
var windW = $(window).width();
var scrollBarW = viewportwidth - windW;
if(!scrollBarW) return 1;
$('html').css('overflow',ovflwTmp);
return (15 / scrollBarW);
}
虽然这不是完美的,但这是我迄今为止能想到的最好的解决方案。我目前正在使用它来确定何时提供高分辨率图像,如果用户缩放到使它们变得模糊的程度。