development

모든 최신 브라우저에서 페이지 확대 / 축소 수준을 감지하는 방법은 무엇입니까?

big-blog 2020. 3. 17. 23:38
반응형

모든 최신 브라우저에서 페이지 확대 / 축소 수준을 감지하는 방법은 무엇입니까?


  1. 모든 최신 브라우저에서 페이지 확대 / 축소 수준을 어떻게 감지합니까? 스레드 는 IE7 및 IE8에서 수행하는 방법을 알려주지 만 좋은 크로스 브라우저 솔루션을 찾을 수 없습니다.

  2. Firefox는 나중에 액세스 할 수 있도록 페이지 확대 / 축소 수준을 저장합니다. 첫 페이지로드시 확대 / 축소 수준을 얻을 수 있습니까? 내가 읽은 곳 은 페이지가로드 된 확대 / 축소 변경이 발생할 때 작동합니다 .

  3. 'zoom'이벤트 를 잡을 방법이 있습니까?

내 계산 중 일부는 픽셀 기반이므로 확대시 변동될 수 있기 때문에 이것이 필요합니다.


@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>

이제이 질문을 처음 받았을 때보 다 훨씬 더 엉망입니다. 내가 찾은 모든 답변과 블로그 게시물을 읽은 내용을 요약하면 다음과 같습니다. 또한 이 페이지를 설정 하여 줌 레벨을 측정하는 모든 방법을 테스트합니다 .

편집 (2011-12-12) : 복제 할 수있는 프로젝트를 추가했습니다 : https://github.com/tombigel/detect-zoom

  • IE8 : screen.deviceXDPI / screen.logicalXDPI(또는 기본 줌에 상대적인 줌 레벨의 경우 screen.systemXDPI / screen.logicalXDPI)
  • IE7 : var body = document.body,r = body.getBoundingClientRect(); return (r.left-r.right)/body.offsetWidth;( 이 예 또는 이 답변 덕분에 )
  • FF3.5 만 해당 : screen.width/ 미디어 쿼리 화면 너비 (아래 참조) ( screen.width장치 픽셀 사용하지만 MQ 너비는 CSS 픽셀 사용 한다는 사실을 이용합니다. Quirksmode 너비 덕분에 )
  • FF3.6 : 알려진 방법 없음
  • FF4 + : 미디어 쿼리 이진 검색 (아래 참조)
  • WebKit : https://www.chromestatus.com/feature/5737866978131968 (의견에 Teo 덕분에)
  • WebKit :으로 원하는 div 크기를 측정합니다 -webkit-text-size-adjust:none.
  • WebKit : ( r72591 이후로 깨짐 ) document.width / jQuery(document).width()( 위의 Dirk van Oosterbosch 에게 감사드립니다 ). 기본 줌 대신 장치 픽셀의 비율을 얻으려면을 곱하십시오 window.devicePixelRatio.
  • 올드 웹킷? (확인되지 ​​않음) : parseInt(getComputedStyle(document.documentElement,null).width) / document.documentElement.clientWidth( 이 답변에서 )
  • 오페라 : document.documentElement.offsetWidth/ position:fixed; width:100%div의 너비 . 여기에서 ( Quirksmode의 너비 테이블 은 버그라고 말합니다; innerWidth는 CSS px 여야합니다). 스크롤바가있는 공간을 포함하여 뷰포트의 너비를 얻기 위해 position : fixed 요소를 사용합니다 . document.documentElement.clientWidth는이 너비를 제외합니다. 2011 년 이래로 깨졌습니다. 더 이상 Opera에서 확대 / 축소 수준을 얻는 방법이 없습니다.
  • 기타 : Sebastian의 플래시 솔루션
  • 신뢰할 수 없음 : 마우스 이벤트를 듣고 screenX의 변경 / clientX의 변경을 측정

Firefox 4에 대한 이진 검색은 다음과 같습니다. 노출 된 위치에 대한 변수를 모르기 때문입니다.

<style id=binarysearch></style>
<div id=dummyElement>Dummy element to test media queries.</div>
<script>
var mediaQueryMatches = function(property, r) {
  var style = document.getElementById('binarysearch');
  var dummyElement = document.getElementById('dummyElement');
  style.sheet.insertRule('@media (' + property + ':' + r +
                         ') {#dummyElement ' +
                         '{text-decoration: underline} }', 0);
  var matched = getComputedStyle(dummyElement, null).textDecoration
      == 'underline';
  style.sheet.deleteRule(0);
  return matched;
};
var mediaQueryBinarySearch = function(
    property, unit, a, b, maxIter, epsilon) {
  var mid = (a + b)/2;
  if (maxIter == 0 || b - a < epsilon) return mid;
  if (mediaQueryMatches(property, mid + unit)) {
    return mediaQueryBinarySearch(
        property, unit, mid, b, maxIter-1, epsilon);
  } else {
    return mediaQueryBinarySearch(
        property, unit, a, mid, maxIter-1, epsilon);
  }
};
var mozDevicePixelRatio = mediaQueryBinarySearch(
    'min--moz-device-pixel-ratio', '', a, b, maxIter, epsilon);
var ff35DevicePixelRatio = screen.width / mediaQueryBinarySearch(
    'min-device-width', 'px', 0, 6000, 25, .0001);
</script>

당신은 시도 할 수 있습니다

var browserZoomLevel = Math.round(window.devicePixelRatio * 100);

브라우저 줌 비율 수준을 제공합니다.

줌 이벤트를 잡기 위해 사용할 수 있습니다

$(window).resize(function() { 
// your code 
});

나에게 Chrome / Webkit의 경우 document.width / jQuery(document).width()작동하지 않았습니다. 창을 작게 만들고 가로 스크롤 막대가 나타나도록 사이트를 확대 document.width / jQuery(document).width()하면 기본 확대 / 축소에서 1과 같지 않았습니다. document.width뷰포트 외부에 문서의 일부가 포함되어 있기 때문 입니다.

사용 window.innerWidth하고 window.outerWidth일했습니다. Chrome에서 어떤 이유로 든 outerWidth는 화면 픽셀로 측정되고 innerWidth는 CSS 픽셀로 측정합니다.

var screenCssPixelRatio = (window.outerWidth - 8) / window.innerWidth;
if (screenCssPixelRatio >= .46 && screenCssPixelRatio <= .54) {
  zoomLevel = "-4";
} else if (screenCssPixelRatio <= .64) {
  zoomLevel = "-3";
} else if (screenCssPixelRatio <= .76) {
  zoomLevel = "-2";
} else if (screenCssPixelRatio <= .92) {
  zoomLevel = "-1";
} else if (screenCssPixelRatio <= 1.10) {
  zoomLevel = "0";
} else if (screenCssPixelRatio <= 1.32) {
  zoomLevel = "1";
} else if (screenCssPixelRatio <= 1.58) {
  zoomLevel = "2";
} else if (screenCssPixelRatio <= 1.90) {
  zoomLevel = "3";
} else if (screenCssPixelRatio <= 2.28) {
  zoomLevel = "4";
} else if (screenCssPixelRatio <= 2.70) {
  zoomLevel = "5";
} else {
  zoomLevel = "unknown";
}

동료와 나는 https://github.com/tombigel/detect-zoom 의 스크립트를 사용했습니다 . 또한 svg 요소를 동적으로 만들고 currentScale 속성을 확인합니다. Chrome 및 대부분의 브라우저에서도 잘 작동합니다. FF에서는 "줌 텍스트 만"기능을 꺼야합니다. SVG는 대부분의 브라우저에서 지원 됩니다. 이 글을 쓰는 시점에서 IE10, FF19 및 Chrome28에서 테스트되었습니다.

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('version', '1.1');
document.body.appendChild(svg);
var z = svg.currentScale;
... more code ...
document.body.removeChild(svg);

이 기사가 엄청나게 도움이되었습니다. yonran에게 큰 감사합니다. 그가 제공 한 기술 중 일부를 구현하면서 발견 한 추가 학습 내용을 전달하고 싶었습니다. FF6 및 Chrome 9에는 JS의 미디어 쿼리에 대한 지원이 추가되어 FF 확대를 결정하는 데 필요한 미디어 쿼리 접근 방식을 크게 단순화 할 수 있습니다. 여기 MDN 문서를 참조 하십시오 . 내 목적을 위해 브라우저가 확대 또는 축소되었는지 여부 만 감지하면 실제 확대 / 축소 비율이 필요하지 않았습니다. 한 줄의 JavaScript로 답변을 얻을 수있었습니다.

var isZoomed = window.matchMedia('(max--moz-device-pixel-ratio:0.99), (min--moz-device-pixel-ratio:1.01)').matches;

이것을 한 줄의 IE8 + 및 Webkit 솔루션과 결합하여 몇 줄의 코드만으로 앱을 공격하는 대다수의 브라우저에서 확대를 감지 할 수있었습니다.


zoom = ( window.outerWidth - 10 ) / window.innerWidth

그게 당신이 필요한 전부입니다.


2016 년 1 월 현재 이에 대한 솔루션이 있습니다. Chrome, Firefox 및 MS Edge 브라우저에서 작동하는지 테스트했습니다.

원칙은 다음과 같습니다. 멀리 떨어진 2 개의 MouseEvent 포인트를 수집하십시오. 각 마우스 이벤트에는 화면 및 문서 좌표가 제공됩니다. 두 좌표계에서 두 점 사이의 거리를 측정합니다. 브라우저 가구로 인해 좌표계간에 가변 고정 오프셋이 있지만 페이지가 확대되지 않은 경우 점 사이의 거리는 동일해야합니다. "먼 거리"(12 픽셀로 지정)를 지정하는 이유는 작은 줌 변경 (예 : 90 % 또는 110 %)을 감지 할 수 있기 때문입니다.

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

단계 :

  1. 마우스 이동 리스너 추가

    window.addEventListener("mousemove", function(event) {
        // handle event
    });
    
  2. 마우스 이벤트에서 4 가지 측정을 캡처하십시오.

    event.clientX, event.clientY, event.screenX, event.screenY
    
  3. 클라이언트 시스템에서 두 지점 사이의 거리 d_c 측정

  4. 스크린 시스템에서 두 지점 사이의 거리 d_s 측정

  5. d_c! = d_s이면 줌이 적용됩니다. 이 둘의 차이는 줌의 양을 알려줍니다.

NB 거리 계산은 거의하지 않습니다. 예를 들어, 이전 마우스와는 거리가 먼 새 마우스 이벤트를 샘플링 할 수 있습니다.

제한 사항 : 사용자가 마우스를 약간 움직인다고 가정하고이 시점까지 확대 / 축소를 알 수 없습니다.


Internet Explorer 7, 8 및 9에서는 다음과 같이 작동합니다.

function getZoom() {
    var screen;

    screen = document.frames.screen;
    return ((screen.deviceXDPI / screen.systemXDPI) * 100 + 0.9).toFixed();
}

반올림 오류를 방지하기 위해 "+0.9"가 추가됩니다 (그렇지 않으면 브라우저 확대 / 축소가 각각 105 % 및 110 %로 설정된 경우 104 % 및 109 %가 표시됨).

IE6에는 줌이 존재하지 않으므로 줌을 확인할 필요가 없습니다.


내가 생각해 낸 것은 :

1)을 확인 position:fixed <div>하여 width: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>

추신 : 이것은 내 첫 번째 게시물입니다, 실수를 용서하십시오


이것은 웹킷 기반 브라우저 (Chrome, Safari)에서 나에게 효과적이었습니다.

function isZoomed() {
    var width, mediaQuery;

    width = document.body.clientWidth;
    mediaQuery = '(max-width: ' + width + 'px) and (min-width: ' + width + 'px)';

    return !window.matchMedia(mediaQuery).matches;
}

Firefox에서는 작동하지 않는 것 같습니다.

이것은 WebKit에서도 작동합니다.

var zoomLevel = document.width / document.body.clientWidth;

기본적으로, 우리는 :

  • window.devicePixelRatio브라우저 수준 줌 * 및 시스템 줌 / 픽셀 밀도를 모두 고려합니다.
    * — Mac / Safari 확대 / 축소 수준은 고려되지 않습니다
  • 미디어 쿼리
  • vw/ vhCSS 단위
  • resize 확대 / 축소 수준 변경시 트리거되는 이벤트는 창 크기를 효과적으로 조정합니다.

일반 UX에는 충분합니다 . UI 디자인이 잘못 될 수있는 확대 / 축소 수준을 감지해야하는 경우

피치 줌은 추적하기 어렵고 현재 고려되지 않습니다.


모바일 기기 (안드로이드 또는 오페라 모바일 크롬으로) 당신은에 의해 줌 감지 할 수 window.visualViewport.scale . https://developer.mozilla.org/en-US/docs/Web/API/Visual_Viewport_API

Safari에서 감지 : document.documentElement.clientWidth / window.innerWidth (장치를 확대하지 않으면 1을 반환)


계산은 여전히 ​​여러 CSS 픽셀을 기반으로합니다. 화면에서 크기가 다릅니다. 이것이 전체 페이지 확대의 요점입니다.

이미지의 각 픽셀에 대해 일반적으로 4 개의 장치 픽셀을 표시하는 192dpi 장치의 브라우저에서 어떤 작업을 원하십니까? 50 % 줌에서이 장치는 이제 하나의 장치 픽셀에 하나의 이미지 픽셀을 표시합니다.


Chrome에서

var ratio = (screen.availWidth / document.documentElement.clientWidth);
var zoomLevel = Number(ratio.toFixed(1).replace(".", "") + "0");

IE이 테스트를하지만, 경우 요소하지 않았다 elem과를

min-width: 100%

그때

window.document.width / elem.clientWidth

브라우저 확대 / 축소 수준 ( document.body.style.zoom요소 포함 )을 제공합니다.


이것은 user800583 답변으로 인해 Chrome 용입니다 ...

나는이 문제에 몇 시간을 보냈고 더 나은 접근법을 찾지 못했습니다.

  • 16 개의 'zoomLevel'이 있으며 10이 아닙니다.
  • Chrome이 전체 화면 / 최대화되면 비율은 window.outerWidth/window.innerWidth입니다. 그렇지 않은 경우 비율은 ~ 인 것처럼 보이지만 (window.outerWidth-16)/window.innerWidth첫 번째 경우는 두 번째 경우에 접근 할 수 있습니다.

그래서 나는 다음에 왔습니다 ...

그러나이 접근법에는 한계가 있습니다. 예를 들어 응용 프로그램 창과 아코디언을 재생하면 (창 너비를 빠르게 확대하고 축소) 줌이 변경되지 않았더라도 줌 레벨 사이에 간격이 생깁니다 (outerWidth 및 innerWidth는 아닐 수 있음) 정확히 동시에 업데이트).

var snap = function (r, snaps)
{
    var i;
    for (i=0; i < 16; i++) { if ( r < snaps[i] ) return i; }
};
var w, l, r;
w = window.outerWidth, l = window.innerWidth;
return snap((w - 16) / l,
            [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
);

그리고 당신이 요인을 원한다면 :

var snap = function (r, snaps, ratios)
{
    var i;
    for (i=0; i < 16; i++) { if ( r < snaps[i] ) return eval(ratios[i]); }
};
var w, l, r;
w = window.outerWidth, l = window.innerWidth;
return snap((w - 16) / l,
            [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
            [ 0.25, '1/3', 0.5, '2/3', 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5 ]
);

이 솔루션은 모바일 전용입니다 (Android에서 테스트).

jQuery(function($){

zoom_level = function(){

    $("body").prepend('<div class="overlay" ' +
                'style="position:fixed; top:0%; left:0%; ' +
                'width:100%; height:100%; z-index:1;"></div>');

    var ratio = $("body .overlay:eq(0)").outerWidth() / $(window).width();
    $("body .overlay:eq(0)").remove();

    return ratio;
}

alert(zoom_level());

});

핀치 이동 직후 확대 / 축소 수준을 원한다면 렌더링 지연으로 인해 약간의 시간 초과를 설정해야 할 것입니다 (그러나 테스트하지 않았기 때문에 확실하지 않습니다).


이 답변은 user1080381 님의 답변에서 devicePixelRatio이 잘못 돌아 왔다는 의견에 근거합니다.

데스크탑, Surface Pro 3 및 Surface Pro 4로 작업 할 때 일부 경우에도이 명령이 잘못 돌아 오는 것을 발견했습니다.

내가 찾은 것은 내 데스크탑에서 작동했지만 SP3과 SP4는 서로 다른 숫자와 데스크탑을 제공한다는 것입니다.

SP3이 내가 기대 한 줌 레벨의 1.5 배로 돌아오고 있음을 알았습니다. 디스플레이 설정을 살펴보면 SP3은 실제로 데스크탑에있는 100 % 대신 150 %로 설정되었습니다.

따라서 주석에 대한 해결책은 반환 된 확대 / 축소 수준을 현재 사용중인 컴퓨터의 규모로 나누는 것입니다.

다음을 수행하여 Windows 설정에서 스케일을 얻을 수있었습니다.

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
double deviceScale = Convert.ToDouble(searcher.Get().OfType<ManagementObject>().FirstOrDefault()["PixelsPerXLogicalInch"]);
int standardPixelPerInch = 96;
return deviceScale / standardPixelPerInch;

SP3의 경우이 코드가 100 % 확대 / 축소로 표시되는 방식입니다.

devicePixelRatio = 1.5
deviceScale = 144
deviceScale / standardPixelPerInch = 1.5
devicePixelRatio / (deviceScale / standardPixelPerInch) = 1

user1080381의 원래 답변에 100을 곱하면 100 (%)의 줌이 제공됩니다.


현재 작동하고 있지만 여전히 브라우저별로 분리해야합니다. Chrome (75) 및 Safari (11.1)에서 성공적으로 테스트되었습니다 (아직 FF 방법은 찾지 못함). 또한 망막 디스플레이에서 정확한 줌 값을 가져오고 크기 조정 이벤트에서 계산이 트리거됩니다.

    private pixelRatio() {
      const styleString = "(min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 1.5),(-moz-min-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5)";
      const chromeRatio = (Math.round((this.window.outerWidth / this.window.innerWidth)*100) / 100);
      const otherRatio = (Math.round(window.devicePixelRatio * 100) / 100);
      const resizeValue = (this.isChrome()) ? chromeRatio : otherRatio;

      return resizeValue || (this.window.matchMedia && this.window.matchMedia(styleString).matches ? 2 : 1) || 1;
    }


  private isChrome():boolean {
    return (!!this.window.chrome && !(!!this.window.opera || this.window.navigator.userAgent.indexOf(' Opera') >= 0))
  }

  private chrome() {
    const zoomChrome = Math.round(((this.window.outerWidth) / this.window.innerWidth)*100) / 100;
    return {
      zoom: zoomChrome,
      devicePxPerCssPx: zoomChrome1 * this.pixelRatio()
    };
  }

여기서는 바뀌지 않습니다! :

<html>
 <head>
  <title></title>
 </head>
<body>
 <div id="xy" style="width:400px;">
  foobar
 </div>
 <div>
  <button onclick="alert(document.getElementById('xy').style.width);">Show</button>
 </div>
</body>
</html>

간단한 html 파일을 만들려면 버튼을 클릭하십시오. 확대 / 축소 수준에 관계없이 너비는 400px입니다 (적어도 firefox 및 ie8에서는)


이것은 누군가를 도울 수도 있고하지 않을 수도 있지만, 내가 시도한 Css 트릭에 관계없이 올바르게 센터링 할 수없는 페이지가 있었기 때문에 JQuery 파일 콜 센터 페이지를 작성했습니다.

브라우저의 확대 / 축소 수준에서 문제가 발생했습니다. 100 %, 125 %, 150 % 등의 여부에 따라 페이지가 이동합니다.

아래 코드는 centerpage.js라는 JQuery 파일에 있습니다.

내 마스터 페이지에는 이미 JQuery에 대한 링크가 있지만 내 페이지에서 JQuery와이 파일을 연결하여 작동시켜야했습니다.

<title>Home Page.</title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/centerpage.js"></script>

centerpage.js:

// centering page element
function centerPage() {
    // get body element
    var body = document.body;

    // if the body element exists
    if (body != null) {
        // get the clientWidth
        var clientWidth = body.clientWidth;

        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var left = (windowWidth - bodyWidth) / 2;

        // this is a hack, but it works for me a better method is to determine the 
        // scale but for now it works for my needs
        if (left > 84) {
            // the zoom level is most likely around 150 or higher
            $('#MainBody').removeClass('body').addClass('body150');
        } else if (left < 100) {
            // the zoom level is most likely around 110 - 140
            $('#MainBody').removeClass('body').addClass('body125');
        }
    }
}


// CONTROLLING EVENTS IN jQuery
$(document).ready(function() {
    // center the page
    centerPage();
});

또한 패널을 중앙에 배치하려는 경우 :

// centering panel
function centerPanel($panelControl) {
    // if the panel control exists
    if ($panelControl && $panelControl.length) {
        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var panelHeight = $panelControl.height();
        var panelWidth = $panelControl.width();

        // centering
        $panelControl.css({
            'position': 'absolute',
            'top': (windowHeight - panelHeight) / 2,
            'left': (windowWidth - panelWidth) / 2
        });

        // only need force for IE6
        $('#backgroundPanel').css('height', windowHeight);
    }
}

이 질문은 오래 전처럼 게시되었지만 오늘은 "확대 및 축소 이벤트 감지 방법"과 같은 대답을 찾고 있었을 때 모든 브라우저에 맞는 하나의 답변을 찾을 수 없었습니다.

Firefox / Chrome / IE8 및 IE9의 경우 확대 / 축소가 window.resize 이벤트를 발생시킵니다. 다음을 사용하여 캡처 할 수 있습니다.

$(window).resize(function() {
//YOUR CODE.
});

FireFox 16+가 JavaScript로 DPPX (확대 / 축소 수준)를 찾는 방법 :

var dppx = (function (precision) {
  var searchDPPX = function(level, min, divisor) {
    var wmq = window.matchMedia;
    while (level >= min && !wmq("(min-resolution: " + (level/divisor) + "dppx)").matches) {
      level--;
    }
    return level;
  };

  var maxDPPX = 5.0; // Firefox 22 has 3.0 as maximum, but testing a bit greater values does not cost much
  var minDPPX = 0.1; // Firefox 22 has 0.3 as minimum, but testing a bit smaller values does not cost anything
  var divisor = 1;
  var result;
  for (var i = 0; i < precision; i++) {
    result = 10 * searchDPPX (maxDPPX, minDPPX, divisor);
    maxDPPX = result + 9;
    minDPPX = result;
    divisor *= 10;
  }

  return result / divisor;
}) (5);

function supportFullCss3()
{
    var div = document.createElement("div");
    div.style.display = 'flex';
    var s1 = div.style.display == 'flex';
    var s2 = 'perspective' in div.style;

    return (s1 && s2);
};

function getZoomLevel()
{
    var screenPixelRatio = 0, zoomLevel = 0;

    if(window.devicePixelRatio && supportFullCss3())
        screenPixelRatio = window.devicePixelRatio;
    else if(window.screenX == '0')
        screenPixelRatio = (window.outerWidth - 8) / window.innerWidth;
    else
    {
        var scr = window.frames.screen;
        screenPixelRatio = scr.deviceXDPI / scr.systemXDPI;
    }

    //---------------------------------------
    if (screenPixelRatio <= .11){ //screenPixelRatio >= .01 &&
      zoomLevel = "-7";
    } else if (screenPixelRatio <= .25) {
      zoomLevel = "-6";
    }else if (screenPixelRatio <= .33) {
      zoomLevel = "-5.5";
    } else if (screenPixelRatio <= .40) {
      zoomLevel = "-5";
    } else if (screenPixelRatio <= .50) {
      zoomLevel = "-4";
    } else if (screenPixelRatio <= .67) {
      zoomLevel = "-3";
    } else if (screenPixelRatio <= .75) {
      zoomLevel = "-2";
    } else if (screenPixelRatio <= .85) {
      zoomLevel = "-1.5";
    } else if (screenPixelRatio <= .98) {
      zoomLevel = "-1";
    } else if (screenPixelRatio <= 1.03) {
      zoomLevel = "0";
    } else if (screenPixelRatio <= 1.12) {
      zoomLevel = "1";
    } else if (screenPixelRatio <= 1.2) {
      zoomLevel = "1.5";
    } else if (screenPixelRatio <= 1.3) {
      zoomLevel = "2";
    } else if (screenPixelRatio <= 1.4) {
      zoomLevel = "2.5";
    } else if (screenPixelRatio <= 1.5) {
      zoomLevel = "3";
    } else if (screenPixelRatio <= 1.6) {
      zoomLevel = "3.3";
    } else if (screenPixelRatio <= 1.7) {
      zoomLevel = "3.7";
    } else if (screenPixelRatio <= 1.8) {
      zoomLevel = "4";
    } else if (screenPixelRatio <= 1.9) {
      zoomLevel = "4.5";
    } else if (screenPixelRatio <= 2) {
      zoomLevel = "5";
    } else if (screenPixelRatio <= 2.1) {
      zoomLevel = "5.2";
    } else if (screenPixelRatio <= 2.2) {
      zoomLevel = "5.4";
    } else if (screenPixelRatio <= 2.3) {
      zoomLevel = "5.6";
    } else if (screenPixelRatio <= 2.4) {
      zoomLevel = "5.8";
    } else if (screenPixelRatio <= 2.5) {
      zoomLevel = "6";
    } else if (screenPixelRatio <= 2.6) {
      zoomLevel = "6.2";
    } else if (screenPixelRatio <= 2.7) {
      zoomLevel = "6.4";
    } else if (screenPixelRatio <= 2.8) {
      zoomLevel = "6.6";
    } else if (screenPixelRatio <= 2.9) {
      zoomLevel = "6.8";
    } else if (screenPixelRatio <= 3) {
      zoomLevel = "7";
    } else if (screenPixelRatio <= 3.1) {
      zoomLevel = "7.1";
    } else if (screenPixelRatio <= 3.2) {
      zoomLevel = "7.2";
    } else if (screenPixelRatio <= 3.3) {
      zoomLevel = "7.3";
    } else if (screenPixelRatio <= 3.4) {
      zoomLevel = "7.4";
    } else if (screenPixelRatio <= 3.5) {
      zoomLevel = "7.5";
    } else if (screenPixelRatio <= 3.6) {
      zoomLevel = "7.6";
    } else if (screenPixelRatio <= 3.7) {
      zoomLevel = "7.7";
    } else if (screenPixelRatio <= 3.8) {
      zoomLevel = "7.8";
    } else if (screenPixelRatio <= 3.9) {
      zoomLevel = "7.9";
    } else if (screenPixelRatio <= 4) {
      zoomLevel = "8";
    } else if (screenPixelRatio <= 4.1) {
      zoomLevel = "8.1";
    } else if (screenPixelRatio <= 4.2) {
      zoomLevel = "8.2";
    } else if (screenPixelRatio <= 4.3) {
      zoomLevel = "8.3";
    } else if (screenPixelRatio <= 4.4) {
      zoomLevel = "8.4";
    } else if (screenPixelRatio <= 4.5) {
      zoomLevel = "8.5";
    } else if (screenPixelRatio <= 4.6) {
      zoomLevel = "8.6";
    } else if (screenPixelRatio <= 4.7) {
      zoomLevel = "8.7";
    } else if (screenPixelRatio <= 4.8) {
      zoomLevel = "8.8";
    } else if (screenPixelRatio <= 4.9) {
      zoomLevel = "8.9";
    } else if (screenPixelRatio <= 5) {
      zoomLevel = "9";
    }else {
      zoomLevel = "unknown";
    }

    return zoomLevel;
};

문제는 사용 된 모니터 유형, 4k 모니터 대 표준 모니터에 있습니다. Chrome은을 사용하여 확대 / 축소 수준을 알려줄 수있는 가장 현명 window.devicePixelRatio합니다. 픽셀 밀도가 무엇인지 알 수 있고 문제에 대해 같은 숫자를 다시보고 할 수 있습니다.

다른 브라우저는별로 없습니다. IE와 Edge는 확대 / 축소 수준을 크게 다르게 처리하므로 최악 일 수 있습니다. 4k 모니터에서 동일한 크기의 텍스트를 얻으려면 표준 모니터에서 100 % 대신 200 %를 선택해야합니다.

2018 년 5 월 현재 가장 인기있는 브라우저, Chrome, Firefox 및 IE11의 줌 레벨을 감지해야합니다. 확대 비율이 무엇인지 말해줍니다. IE의 경우 실제로 200 % 인 4K 모니터에서도 100 %를보고하지만 텍스트 크기는 실제로 동일합니다.

바이올린이 있습니다 : https://jsfiddle.net/ae1hdogr/

다른 브라우저에서 찌르고 바이올린을 업데이트하려는 사람이 있다면 그렇게하십시오. 내 주요 목표는 사람들이 내 웹 응용 프로그램을 사용하기 위해 100 %보다 큰 확대 / 축소 비율을 사용하고 있는지 여부를 감지하고 이보다 작은 확대 / 축소 비율을 나타내는 알림을 표시하도록이 3 개의 브라우저를 다루는 것입니다.

참고 URL : https://stackoverflow.com/questions/1713771/how-to-detect-page-zoom-level-in-all-modern-browsers

반응형