在Safari中使用jQuery检测页面缩放更改

时间:2011-05-28 17:18:08

标签: javascript jquery

我在包含position:fixed元素的web应用程序中遇到Safari问题。当页面缩小(小于100%)时,事情就会中断,需要通过调用函数来修复。所以我想检测用户的缩放。我刚才发现了这个jQueryPlug:

http://mlntn.com/2008/12/11/javascript-jquery-zoom-event-plugin/

http://mlntn.com/demos/jquery-zoom/

它会检测可能导致页面缩放级别更改的键盘和鼠标事件。很公平。它适用于当前的FF和IE,但不适用于Safari。在当前的WebKit浏览器中可以做些什么来做同样的事情?

3 个答案:

答案 0 :(得分:22)

这不是this question的直接副本,因为它涉及Mobile Safari,但同样的解决方案也可以。

  

放大时,会调整window.innerWidth,但不会调整document.documentElement.clientWidth:

var zoom = document.documentElement.clientWidth / window.innerWidth;

此外,您应该能够使用onresize事件处理程序(或jQuery的.resize())来检查:

var zoom = document.documentElement.clientWidth / window.innerWidth;
$(window).resize(function() {
    var zoomNew = document.documentElement.clientWidth / window.innerWidth;
    if (zoom != zoomNew) {
        // zoom has changed
        // adjust your fixed element
        zoom = zoomNew
    }
});

答案 1 :(得分:1)

yonran构建了一个可以执行检测的漂亮插件。以下是他之前关于StackOverflow的answered问题。它适用于大多数浏览器。应用程序就像这样简单:

window.onresize = function onresize() {
  var r = DetectZoom.ratios();
  zoomLevel.innerHTML =
    "Zoom level: " + r.zoom +
    (r.zoom !== r.devicePxPerCssPx
        ? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
        : "");
}

Demo

答案 2 :(得分:1)

  

srceen.width是固定值,但window.innerWidth值将根据缩放效果更改。请尝试以下代码:

 $(window).resize(function() {
   if(screen.width == window.innerWidth){
       alert("you are on normal page with 100% zoom");
   } else if(screen.width > window.innerWidth){
       alert("you have zoomed in the page i.e more than 100%");
   } else {
       alert("you have zoomed out i.e less than 100%");
   }
});
相关问题