Detect page zoom change with jQuery in Safari

后端 未结 3 1332
半阙折子戏
半阙折子戏 2020-11-30 05:01

I have a problem with Safari in a web application that contains a position:fixed element. When the page is zoomed out (smaller 100%) things break and would need to be fixed

相关标签:
3条回答
  • 2020-11-30 05:46

    There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:

    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

    0 讨论(0)
  • 2020-11-30 05:48

    srceen.width is fixed value but where as window.innerWidth value will change as per the zoom effect. please try the below code:

     $(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%");
       }
    });
    
    0 讨论(0)
  • 2020-11-30 06:00

    It's not a direct duplicate of this question since that deals with Mobile Safari, but the same solution will work.

    When you zoom in, window.innerWidth is adjusted, but document.documentElement.clientWidth is not, therefore:

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

    Furthermore, you should be able to use the onresize event handler (or jQuery's .resize()) to check for this:

    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
        }
    });
    
    0 讨论(0)
提交回复
热议问题