如何在所有现代浏览器中检测页面缩放级别?虽然这篇文章讲述了如何在IE7和IE8中做到这一点,但我找不到一个好的跨浏览器解决方案。
Firefox存储页面缩放级别以供将来访问。在第一页加载,我能得到缩放级别吗?在某个地方,我读到当页面加载后发生缩放变化时,它是有效的。
有办法捕捉'缩放'事件吗?
我需要这个,因为我的一些计算是基于像素的,他们可能会在放大时波动。
@tfl给出的修改样本
放大时,此页面会提示不同的高度值。(jsFiddle)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"/></script>
</head>
<body>
<div id="xy" style="border:1px solid #f00; width:100px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sollicitudin tortor in lacus tincidunt volutpat. Integer dignissim imperdiet mollis. Suspendisse quis tortor velit, placerat tempor neque. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent bibendum auctor lorem vitae tempor. Nullam condimentum aliquam elementum. Nullam egestas gravida elementum. Maecenas mattis molestie nisl sit amet vehicula. Donec semper tristique blandit. Vestibulum adipiscing placerat mollis.</div>
<button onclick="alert($('#xy').height());">Show</button>
</body>
</html>
我想到的是:
1)制作一个位置:固定<div>宽度:100% (id=zoomdiv)
2)页面加载时:
zoomlevel=$("#zoomdiv").width()*1.0 / screen.availWidth
它适用于我的ctrl+和ctrl-缩放。
或者我可以添加一行到$(window).onresize()事件,以获得活动缩放级别
代码:
<script>
var zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
$(window).resize(function(){
zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
alert(zoom);
});
</script>
<body>
<div id=zoomdiv style="width:100%;position:fixed;"></div>
</body>
附注:这是我的第一个帖子,请原谅任何错误
I found this article enormously helpful. Huge thanks to yonran. I wanted to pass on some additional learning I found while implementing some of the techniques he provided. In FF6 and Chrome 9, support for media queries from JS was added, which can greatly simplify the media query approach necessary for determining zoom in FF. See the docs at MDN here. For my purposes, I only needed to detect whether the browser was zoomed in or out, I had no need for the actual zoom factor. I was able to get my answer with one line of JavaScript:
var isZoomed = window.matchMedia('(max--moz-device-pixel-ratio:0.99), (min--moz-device-pixel-ratio:1.01)').matches;
结合IE8+和Webkit解决方案(它们也是单行的),我能够在只有几行代码的情况下检测到绝大多数浏览器的缩放效果。