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

Detect page zoom change with jQuery in Safari

本文关键字:缩放 检测 jQuery Safari      更新时间:2023-09-26

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

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

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

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

这不是这个问题的直接重复,因为它涉及Mobile Safari,但同样的解决方案也会起作用。

放大时,window.innerWidth会调整,但document.dococumentElement.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
    }
});

有一个从yonran构建的漂亮插件可以进行检测。以下是他之前在StackOverflow上回答的问题。它适用于大多数浏览器。应用程序就这么简单:

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
        : "");
}

演示

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%");
   }
});

区分窗口大小调整、浏览器缩放更改和系统dpi更改

;(() => {
  const last = {
    devicePixelRatio: devicePixelRatio,
    innerWidth: innerWidth,
    innerHeight: innerHeight,
    outerWidth: outerWidth,
    outerHeight: outerHeight,
  }
      
  const browser = navigator.appVersion.includes('WebKit')
  
  const almostZero = n => n <= 1 && n >= -1
  
  window.addEventListener('resize', () => {
    if (last.devicePixelRatio !== devicePixelRatio) {
      if (browser ? almostZero(last.innerWidth - innerWidth) && almostZero(last.innerHeight - innerHeight)
          :almostZero(last.outerWidth - outerWidth) && almostZero(last.outerHeight - outerHeight)) {
        console.log('system wide dpi change')
      } else {
        console.log('browser level zoom change')
      }
    } else {
      console.log('window resize')
    }
    last.devicePixelRatio = devicePixelRatio
    last.innerWidth = innerWidth
    last.innerHeight = innerHeight
    last.outerWidth = outerWidth
    last.outerHeight = outerHeight
  })
})()

适用于Chrome&Windows 上的Firefox