How to detect page zoom level in all modern browsers?

后端 未结 28 1833
慢半拍i
慢半拍i 2020-11-21 05:27
  1. How can I detect the page zoom level in all modern browsers? While this thread tells how to do it in IE7 and IE8, I can\'t find a good cross-browser solution.

28条回答
  •  执念已碎
    2020-11-21 06:11

    I have a solution for this as of Jan 2016. Tested working in Chrome, Firefox and MS Edge browsers.

    The principle is as follows. Collect 2 MouseEvent points that are far apart. Each mouse event comes with screen and document coordinates. Measure the distance between the 2 points in both coordinate systems. Although there are variable fixed offsets between the coordinate systems due to the browser furniture, the distance between the points should be identical if the page is not zoomed. The reason for specifying "far apart" (I put this as 12 pixels) is so that small zoom changes (e.g. 90% or 110%) are detectable.

    Reference: https://developer.mozilla.org/en/docs/Web/Events/mousemove

    Steps:

    1. Add a mouse move listener

      window.addEventListener("mousemove", function(event) {
          // handle event
      });
      
    2. Capture 4 measurements from mouse events:

      event.clientX, event.clientY, event.screenX, event.screenY
      
    3. Measure the distance d_c between the 2 points in the client system

    4. Measure the distance d_s between the 2 points in the screen system

    5. If d_c != d_s then zoom is applied. The difference between the two tells you the amount of zoom.

    N.B. Only do the distance calculations rarely, e.g. when you can sample a new mouse event that's far from the previous one.

    Limitations: Assumes user will move the mouse at least a little, and zoom is unknowable until this time.

提交回复
热议问题