Development Tip

브라우저 간 확대 방지

yourdevel 2020. 12. 8. 20:07
반응형

브라우저 간 확대 방지


지도와 같은 도구의 경우 브라우저 확대 / 축소 기능비활성화하고 싶습니다 . (나는 이것이 일반적으로 나쁜 생각이라는 것을 알고 있지만 일부 특정 웹 사이트에는 필요합니다).

키보드 단축키 CTRL +/ CTRL -를 듣고을 추가하여 성공적으로 수행했습니다 e.preventDefault(). 그러나 이것이 브라우저의 확대 / 축소 메뉴에서 확대 / 축소를 변경하는 것을 막지는 않습니다.

나는 시도했다 :

  • CSS 사용 : zoom: reset;Chrome 에서는 작동 하지만 ( 작동 예제는이 페이지 참조 ) Firefox에서는 전혀 작동하지 않습니다.

  • 다양한 질문 / 답변에서

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    그러나 이것은 모바일에서만 작동하는 것 같습니다.


브라우저 간 확대 / 축소를 방지하는 방법은 무엇입니까?


이 코드를 사용하여 Ctrl + 또는 Ctrl- 또는 Ctrl 키 + 마우스 휠 위 또는 아래로 브라우저 확대를 비활성화 할 수 있습니다.

$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '61' || event.which == '107' || event.which == '173' || event.which == '109'  || event.which == '187'  || event.which == '189'  ) ) {
        event.preventDefault();
     }
    // 107 Num Key  +
    // 109 Num Key  -
    // 173 Min Key  hyphen/underscor Hey
    // 61 Plus key  +/= key
});

$(window).bind('mousewheel DOMMouseScroll', function (event) {
       if (event.ctrlKey == true) {
       event.preventDefault();
       }
});

여기에서 데모를 확인하십시오. http://jsfiddle.net/VijayDhanvai/4m3z3knd/


나는 브라우저 개발자의 명확한 진술을 의미하는 "신뢰할 수있는"대답을 실제로 찾지 못했습니다. 그러나 내가 찾은 비슷한 질문에 대한 모든 답변 (예 : 질문 또는 저것 )은 동일한 것을 제안합니다. 브라우저의 확대 / 축소 기능은 사용자의 이익을 위해 존재하며 일부 브라우저 (예 : Firefox)는 단순히 허용하지 않습니다. 웹 사이트 제작자가이 옵션을 제거합니다.


이 문서 는 작성자가 확대 / 축소를 비활성화하도록 허용하는 것이 데스크톱이 아닌 모바일 장치에서는 좋은 생각 일 수있는 이유를 설명 할 수 있습니다.

간단히 말해, 계산 된 자동 확대 / 축소가 부적절하다는 것을 알고있는 경우 모바일 장치에서 처음에 웹 사이트를 자동 확대하지 못하도록해야 할 수 있습니다. 데스크톱에서는 자동 확대 / 축소 기능이 없으므로 사용자가 웹 사이트를 방문 할 때 의도 한 그대로 표시됩니다. 그런 다음 페이지를 확대 / 축소해야한다고 결정하면 그렇게하지 못하도록 할 이유가 없습니다.


나열한 솔루션은 다음과 같습니다.


할 수있는 일은 브라우저 확대 / 축소 이벤트 (ctrl + "+")를 듣고 window.devicePixelRatio를 확인하는 것입니다.

그런 다음 body 요소에 HTML5 배율 변환을 적용하여 동일한 비율로 축소합니다. 따라서 기본적으로 기능을 막을 수는 없지만 동일한 크기로 부정적인 효과를 적용 할 수 있습니다.

POC 코드 :

 <body style="position: absolute;margin: 0px;">
        <div style="width: 300px; height: 200px; border: 1px solid black;">
            Something is written here
        </div>
        <script>
            var keyIncrease = [17, 61];
            var keyDecrease = [17, 173];
            var keyDefault = [17, 48];
            var listenMultiKeypress = function(keys, callback){
                var keyOn = [];
                for(var i=0; i<keys.length; i++){
                    keyOn[i] = false;
                }
                addEventListener('keydown', function(e){
                    var keyCode = e.which;
                    console.log(keyCode);
                    var idx = keys.indexOf(keyCode);
                    if(idx!=-1){
                        keyOn[idx] = true;
                    }
                    console.log(keyOn);
                    for(var i=0; i<keyOn.length; i++){
                        if(!keyOn[i]){
                            return;
                        }
                    }
                    setTimeout(callback, 100);
                });
                addEventListener('keyup', function(e){
                    var keyCode = e.which;
                    var idx = keys.indexOf(keyCode);
                    if(idx!=-1){
                        keyOn[idx] = false;
                    }
                    console.log(keyOn);
                });
            };
            var previousScale = 1;
            var previousDevicePixelRatio;
            var neutralizeZoom = function(){
                //alert('caught');
                var scale = 1/window.devicePixelRatio;

                document.body.style.transform = 'scale('+(1/previousScale)+')';
                document.body.style.transform = 'scale('+scale+')';
                var widthDiff = parseInt(getComputedStyle(window.document.body).width)*(scale-1);
                var heightDiff = parseInt(getComputedStyle(window.document.body).height)*(scale-1);
                document.body.style.left = widthDiff/2 + 'px';
                document.body.style.top = heightDiff/2 + 'px';
                previousScale = scale;
            };

            listenMultiKeypress(keyIncrease, neutralizeZoom);
            listenMultiKeypress(keyDecrease, neutralizeZoom);
            listenMultiKeypress(keyDefault, neutralizeZoom);
            neutralizeZoom();
        </script>
    </body>
</html>

따라서 언급했듯이 실제로는 불가능합니다. 그러나 여전히 그것에 대해 현명 할 수있는 몇 가지 방법이 있습니다.

5 개의 주요 브라우저 중 3 개는 모두 브라우저의 확대 / 축소 수준을 볼 수 있도록합니다. 또한 브라우저가 확대되면 window.onresize 이벤트가 발생합니다.

IE:      event.view.devicePixelRatio           OR window.view.devicePixelRatio
Chrome:  event.currentTarget.devicePixelRatio  OR window.devicePixelRatio
Firefox: event.originalTarget.devicePixelRatio OR window.devicePixelRatio
Safari:  /* Not possible */
Opera:   /* Not possible */

I think the stuff after OR works based on something I noticed as I was messing around. The first ones I know work in at least the latest version of each one. Note that Safari and Opera both have the devicePixelRatio, however both never change. It's always just 1.

The above is your easy way if you don't care that much. If you do, then you could try out the detect-zoom script, which I came across while looking for solutions to Safari and Opera.

So what you can now do is get the zoom level, and then offset your zoom to where it doesn't do anything. So if I force my browser to 50% zoom, you just go to 200%. Thus, no change. Of course it will be a bit more complicated, you'll have to store the last browser zoom, the new browser zoom, and do some slightly more complicated math, but based on what you already have, that should be a breeze.

Another idea might be to just listen for a resize event, and calculate based off the new visible size, but that might cause issues if the window is just resized. I think the above is going to be your best option, with perhaps a fallback alert to warn the user not to zoom if necessary.


Insert the following into your HTML:

For Mobiles: Insert between the '< head>...< /head>' tag.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">

For Cross-Browsers: Insert just after start '< body>...' tag.

<script>
  document.body.addEventListener("wheel", e=>{
    if(e.ctrlKey)
      event.preventDefault();//prevent zoom
  });
</script>

I updated code Vijay code:

$(document).ready(function(){
 var keyCodes = [61, 107, 173, 109, 187, 189];

 $(document).keydown(function(event) {   
   if (event.ctrlKey==true && (keyCodes.indexOf(event.which) != -1)) {
     alert('disabling zooming'); 
     event.preventDefault();
    }
 });

 $(window).bind('mousewheel DOMMouseScroll', function (event) {
    if (event.ctrlKey == true) {
      alert('disabling zooming'); 
      event.preventDefault();
    }
  });
});

This solution is cross-platform (OS / Win) for desktop browsers.


It is simple:

function load(){
  document.body.addEventListener("wheel", zoomShortcut); //add the event
}

function zoomShortcut(e){
  if(e.ctrlKey){            //[ctrl] pressed?
    event.preventDefault();  //prevent zoom
    if(e.deltaY<0){        //scrolling up?
                            //do something..
      return false;
    }
    if(e.deltaY>0){        //scrolling down?
                            //do something..
      return false;
    }
  }
}
p {
  display: block;
  background-color: #eeeeee;
  height: 100px;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Mousewheel control!</title>
  </head>
  <body onload="load()">
    <p>If your Mouse is in this Box, you can't zoom.</p>
  </body>
</html>


$(document).ready(function () {
      $(document).keydown(function (event) {
          if (event.ctrlKey == true && (event.which == '107' || event.which == '109' || event.which == '187' || event.which == '189'))
           {
               event.preventDefault();
           }
       });

           $(window).bind('mousewheel DOMMouseScroll', function (event) {
               if (event.ctrlKey == true) {
                   event.preventDefault();
               }

      });
  })

Have you tried ...

$("body").css({
     "-moz-transform":"scale(1)",
     "-webkit-transform":"scale(1)",
     "-o-transform":"scale(1)",
     "-ms-transform":"scale(1)"
});

I've used this type of code to set or re-set the scale.

참고URL : https://stackoverflow.com/questions/27116221/prevent-zoom-cross-browser

반응형