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

StackOverflow https://stackoverflow.com/questions/1713771

문제

  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 픽셀을 사용합니다. 퀴크 스 모드 너비)
  • FF3.6: 알려진 방법이 없습니다
  • ff4+: 미디어 쿼리 바이너리 검색 (아래 참조)
  • 웹 키트: https://www.chromestatus.com/feature/5737866978131968 (의견에 Teo에게 감사합니다)
  • 웹 키트: DIV의 선호하는 크기를 측정하십시오 -webkit-text-size-adjust:none.
  • 웹 키트: (이후 부서진 R72591) document.width / jQuery(document).width() (감사합니다 위의 Dirk van Oosterbosch). 장치 픽셀 측면에서 비율을 얻으려면 (기본 줌에 비해) window.devicePixelRatio.
  • 오래된 웹 키? (검증되지 않음) : parseInt(getComputedStyle(document.documentElement,null).width) / document.documentElement.clientWidth (에서 이 답변)
  • 오페라: document.documentElement.offsetWidth / a의 너비 position:fixed; width:100% div. 여기에서 (QuirksMode의 너비 테이블 버그라고 말합니다. 내면은 CSS PX이어야합니다). 우리는 위치를 사용합니다 : 고정 요소는 뷰포트의 너비를 얻습니다. 스크롤 바가있는 공간을 포함합니다; document.documentElement.clientWidth는이 너비를 제외합니다. 이것은 2011 년 언젠가부터 깨졌습니다. 나는 더 이상 오페라에서 줌 레벨을 얻는 방법이 없다.
  • 다른: Sebastian의 플래시 솔루션
  • 신뢰할 수없는 : 마우스 이벤트를 듣고 ClientX의 Screenx / Change의 변경 측정

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 일했다. 크롬에서 어떤 이유로, 외피는 화면 픽셀로 측정되며 내면은 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 포인트를 수집하십시오. 각 마우스 이벤트에는 화면 및 문서 좌표가 함께 제공됩니다. 두 좌표계에서 2 점 사이의 거리를 측정하십시오. 브라우저 가구로 인해 좌표계간에 가변적 인 고정 오프셋이 있지만 거리 페이지가 확대되지 않으면 포인트간에 동일해야합니다. "멀리 떨어져"(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. 클라이언트 시스템의 2 점 사이의 거리 d_c 측정

  4. 화면 시스템의 2 점 사이의 거리 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) a position:fixed <div> ~와 함께 width:100% (id = Zoomdiv)

2) 페이지가로드 될 때 :

zoomlevel=$("#zoomdiv").width()*1.0 / screen.availWidth

그리고 그것은 나를 위해 일했습니다 ctrl+ 그리고 ctrl- 축소.

또는 라인을 a에 추가 할 수 있습니다 $(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>

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

이것은 WebKit 기반 브라우저 (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/vh CSS 단위
  • resize 줌 레벨 변경시 트리거되는 이벤트는 창 변경의 효과적인 크기를 유발합니다.

그것은 충분해야합니다 정상 ux. 잘못된 UI 디자인의 부호 일 수있는 줌 레벨을 감지 해야하는 경우.

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

이동하는 장치 (Android 또는 Opera Mobile 용 Chrome 포함) 줌을 감지 할 수 있습니다. Window.visualviewport.scale. https://developer.mozilla.org/en-us/docs/web/api/visual_viewport_api

사파리에서 탐지 : Document.DocumentElement.clientWidth / Window.innerWidth (장치에서 확대 / 축소가 없으면 1 반환).

계산은 여전히 ​​CSS 픽셀 수를 기반으로 합니다.이제 화면에서는 크기가 다를 뿐입니다.이것이 전체 페이지 확대의 핵심입니다.

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

크롬에서

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 대답 ...

나는이 문제에 대해 몇 시간을 보냈고 더 나은 접근 방식을 찾지 못했지만 :

  • 10이 아닌 16 개의 '줌 레벨'이 있습니다
  • Chrome이 전체 화면/최대화되면 비율은 IS입니다 window.outerWidth/window.innerWidth, 그리고 그렇지 않을 때는 비율이 (window.outerWidth-16)/window.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 ]
);

이 솔루션이 있습니다 모바일 전용 (안드로이드로 테스트) :

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의 방법을 찾지 못함). 또한 Retina 디스플레이에서 줌 값을 올바르게 가져오고 Resize Event에서 계산이 트리거됩니다.

    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.
});

JavaScript와 함께 DPPX (Zoom Level)를 찾기 위해 Firefox 16+의 해결 방법 :

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/

누군가 다른 브라우저에서 찌르고 바이올린을 업데이트하려면 그렇게하십시오. 저의 주요 목표는이 3 개의 브라우저를 커버하여 사람들이 웹 애플리케이션을 사용하여 100% 이상의 줌 팩터를 사용하고있는 경우 내 웹 응용 프로그램을 사용하고 Lessor Zoom Factor를 제안하는 통지를 표시하는 것이 었습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top