티스토리 뷰

HTML CSS JS

JS) Mobile viewport size fit

Programmers 2021. 9. 24. 07:41
반응형

To support various device viewport size specially mobile device has portrait and landscape, scale up and down, website have to adjust various enviorment

 

js Code - it is widely used

function initScale()   {
   var ress = navigator.userAgent;
   if (ress.indexOf("Android 1.", 0) > -1 ){ 
        if (ress.indexOf("480", 0) > -1 ) { // 480x800
            var per = 0.5226824457593688;
        } else if(ress.indexOf("600", 0) > -1 ) { // 600 x 1024
            var per = 0.681
        } else if(ress.indexOf("1280", 0) > -1 ) { // 800 x 1280
            var per = 0.631
        }
    } else {
        var dh = window.innerHeight;
        var dw = window.innerWidth;
        var cw = parseInt( $('#contentsArea').css('width') );
        var ch = parseInt( $('#contentsArea').css('height') );
        var per = dw/cw;
        var per2 =dh/ch;
        if(per > per2 ){
            per = per2;
        }
        var gapH = ( dh - (ch*per) )/2;
        var gapW = ( dw - (cw*per) )/2        
     } 
     $("#contentsArea").css('transform', 'scale('+per+','+per+')');
     $('body').css('margin-top', gapH );
     $('body').css('margin-left', gapW );
}
window.onresize = function(){
    initScale();
}
window.onload = function() {
    initScale();
}

※ Specific div scale in html doc is adjusted. When loading and changing window, calling it and adjust window size.

 

More easy way.
1. wrap is specifit div width
2. toFixed function change number to string.

Calculate div ratio contrast with screen and adjust this ratio.

var initial_scale = (screen.width / $('#wrap').width()).toFixed(4);
$('meta[name=viewport]')
.attr('content','"width=device-width,initial-scale='+initial_scale+', maximum-scale=2.0, user-scalable=yes"');

$('meta[name=viewport]') is code to access to meta tage viewport.
Normally viewport is on the top page. If bottom is reset, last setting viewport is adjusted.

 

https://doolyit.tistory.com/151

 

화면크기 모바일에 맞추기/ Viewport 의 init-scale 자바스크립트로 접근하여 조정하기, clientHeight, wind

웹사이트 개발시 모바일을 지원하려면 다양한 모바일 기기의 크기에 맞게 작업을 해줘야 합니다. 게다가 모바일 기기는 가로/세로로 변환이 가능하고 사용자가 확대축소 등을 할 수 있기 때문

doolyit.tistory.com

 

반응형

'HTML CSS JS' 카테고리의 다른 글

JS) 브라우저 구분하는 방법 코드  (0) 2021.10.04
CSS) 변환 3D 속성  (0) 2021.09.24
CSS) 변환 2D 속성 transform: translate(30px, 30px)  (0) 2021.09.23
CSS) transform 변환 2D 속성  (0) 2021.09.15
CSS) transform  (0) 2021.09.15
댓글
공지사항